Bundle OCI Auth method (#7422)

This commit is contained in:
Jim Kalafut
2019-09-04 16:46:00 -07:00
committed by GitHub
parent 01d1d94a0c
commit 96b3af9f00
321 changed files with 23547 additions and 1726 deletions

View File

@@ -28,6 +28,7 @@ import (
credCF "github.com/hashicorp/vault-plugin-auth-cf"
credGcp "github.com/hashicorp/vault-plugin-auth-gcp/plugin"
credOIDC "github.com/hashicorp/vault-plugin-auth-jwt"
credOCI "github.com/hashicorp/vault-plugin-auth-oci"
credAws "github.com/hashicorp/vault/builtin/credential/aws"
credCert "github.com/hashicorp/vault/builtin/credential/cert"
credGitHub "github.com/hashicorp/vault/builtin/credential/github"
@@ -162,10 +163,11 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) {
"aws": &credAws.CLIHandler{},
"centrify": &credCentrify.CLIHandler{},
"cert": &credCert.CLIHandler{},
"cf": &credCF.CLIHandler{},
"cf": &credCF.CLIHandler{},
"gcp": &credGcp.CLIHandler{},
"github": &credGitHub.CLIHandler{},
"ldap": &credLdap.CLIHandler{},
"oci": &credOCI.CLIHandler{},
"oidc": &credOIDC.CLIHandler{},
"okta": &credOkta.CLIHandler{},
"pcf": &credCF.CLIHandler{}, // Deprecated.

12
go.mod
View File

@@ -42,7 +42,7 @@ require (
github.com/go-test/deep v1.0.2
github.com/gocql/gocql v0.0.0-20190402132108-0e1d5de854df
github.com/gogo/protobuf v1.2.1
github.com/golang/protobuf v1.3.1
github.com/golang/protobuf v1.3.2
github.com/google/go-github v17.0.0+incompatible
github.com/google/go-metrics-stackdriver v0.0.0-20190816035513-b52628e82e2a
github.com/google/go-querystring v1.0.0 // indirect
@@ -59,7 +59,7 @@ require (
github.com/hashicorp/go-sockaddr v1.0.2
github.com/hashicorp/go-syslog v1.0.0
github.com/hashicorp/go-uuid v1.0.1
github.com/hashicorp/golang-lru v0.5.1
github.com/hashicorp/golang-lru v0.5.3
github.com/hashicorp/hcl v1.0.0
github.com/hashicorp/nomad/api v0.0.0-20190412184103-1c38ced33adf
github.com/hashicorp/raft v1.1.1
@@ -71,6 +71,7 @@ require (
github.com/hashicorp/vault-plugin-auth-gcp v0.5.2-0.20190814210049-1ccb3dc10102
github.com/hashicorp/vault-plugin-auth-jwt v0.5.2-0.20190814210057-5e4c92d2b835
github.com/hashicorp/vault-plugin-auth-kubernetes v0.5.2-0.20190826163451-8461c66275a9
github.com/hashicorp/vault-plugin-auth-oci v0.0.0-20190904175623-97c0c0187c5c
github.com/hashicorp/vault-plugin-database-elasticsearch v0.0.0-20190814210117-e079e01fbb93
github.com/hashicorp/vault-plugin-secrets-ad v0.5.3-0.20190814210122-0f2fd536b250
github.com/hashicorp/vault-plugin-secrets-alicloud v0.5.2-0.20190814210129-4d18bec92f56
@@ -88,6 +89,7 @@ require (
github.com/joyent/triton-go v0.0.0-20190112182421-51ffac552869
github.com/keybase/go-crypto v0.0.0-20190403132359-d65b6b94177f
github.com/kr/pretty v0.1.0
github.com/kr/pty v1.1.3 // indirect
github.com/kr/text v0.1.0
github.com/lib/pq v1.2.0
github.com/mattn/go-colorable v0.1.2
@@ -101,7 +103,7 @@ require (
github.com/ncw/swift v1.0.47
github.com/oklog/run v1.0.0
github.com/onsi/ginkgo v1.7.0 // indirect
github.com/oracle/oci-go-sdk v5.15.0+incompatible
github.com/oracle/oci-go-sdk v7.0.0+incompatible
github.com/ory/dockertest v3.3.4+incompatible
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.8.1
@@ -118,10 +120,10 @@ require (
go.etcd.io/bbolt v1.3.2
go.etcd.io/etcd v0.0.0-20190412021913-f29b1ada1971
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4
golang.org/x/net v0.0.0-20190620200207-3b0461eec859
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7
golang.org/x/oauth2 v0.0.0-20190402181905-9f3314589c9a
google.golang.org/api v0.5.0
google.golang.org/genproto v0.0.0-20190513181449-d00d292a067c
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64
google.golang.org/grpc v1.22.0
gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce
gopkg.in/ory-am/dockertest.v3 v3.3.4

26
go.sum
View File

@@ -147,6 +147,8 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc=
github.com/frankban/quicktest v1.4.1 h1:Wv2VwvNn73pAdFIVUQRXYDFp31lXKbqblIXo/Q5GPSg=
github.com/frankban/quicktest v1.4.1/go.mod h1:36zfPVQyHxymz4cH7wlDmVwDrJuljRB60qkgn7rorfQ=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fullsailor/pkcs7 v0.0.0-20190404230743-d7302db945fa h1:RDBNVkRviHZtvDvId8XSGPu3rmpmSe+wKRcEWNgsfWU=
@@ -195,6 +197,8 @@ github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
@@ -207,6 +211,8 @@ github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
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-metrics-stackdriver v0.0.0-20190816035513-b52628e82e2a h1:qoxSc7PsKuc/RjXf5CB6rRFr5FQSpHM4iIqQfEazLhI=
@@ -269,6 +275,8 @@ github.com/hashicorp/go-hclog v0.9.2 h1:CG6TE5H9/JXsFWJCfoIVpKFIkFe6ysEuHirp4DxC
github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
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-immutable-radix v1.1.0 h1:vN9wG1D6KG6YHRTWr8512cxGOVgTMEfgEdSj/hr8MPc=
github.com/hashicorp/go-immutable-radix v1.1.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-memdb v1.0.2 h1:AIjzJlwIxz2inhZqRJZfe6D15lPeF0/cZyS1BVlnlHg=
github.com/hashicorp/go-memdb v1.0.2/go.mod h1:I6dKdmYhZqU0RJSheVEWgTNWdVQH5QvTgIUQ0t/t32M=
github.com/hashicorp/go-msgpack v0.5.3 h1:zKjpN5BK/P5lMYrLmBHdBULWbJ0XpYR+7NGzqkZzoD4=
@@ -307,6 +315,8 @@ github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.3 h1:YPkqC67at8FYaadspW/6uE0COsBxS2656RLEr8Bppgk=
github.com/hashicorp/golang-lru v0.5.3/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=
@@ -339,6 +349,8 @@ github.com/hashicorp/vault-plugin-auth-jwt v0.5.2-0.20190814210057-5e4c92d2b835
github.com/hashicorp/vault-plugin-auth-jwt v0.5.2-0.20190814210057-5e4c92d2b835/go.mod h1:Ti2NPndKhSGpSL6gWg11n7TkmuI7318BIPeojayIVRU=
github.com/hashicorp/vault-plugin-auth-kubernetes v0.5.2-0.20190826163451-8461c66275a9 h1:PjbIf3mlPBJopQSJstQAhVbdGTVZ/W35RZtm/GCOTUs=
github.com/hashicorp/vault-plugin-auth-kubernetes v0.5.2-0.20190826163451-8461c66275a9/go.mod h1:qkrONCr71ckSCTItJQ1j9uet/faieZJ5c7+GZugTm7s=
github.com/hashicorp/vault-plugin-auth-oci v0.0.0-20190904175623-97c0c0187c5c h1:z6LQZvs1OtoVy2XgbgNhiDgp0U62Xbstn7/cgNZvh6g=
github.com/hashicorp/vault-plugin-auth-oci v0.0.0-20190904175623-97c0c0187c5c/go.mod h1:YAl51RsYRihPbSdnug1NsvutzbRVfrZ12FjEIvSiOTs=
github.com/hashicorp/vault-plugin-database-elasticsearch v0.0.0-20190814210117-e079e01fbb93 h1:kXTV1ImOPgDGZxAlbEQfiXgnZY/34vfgnZVhI/tscmg=
github.com/hashicorp/vault-plugin-database-elasticsearch v0.0.0-20190814210117-e079e01fbb93/go.mod h1:N9XpfMXjeLHBgUd8iy4avOC4mCSqUC7B/R8AtCYhcfE=
github.com/hashicorp/vault-plugin-secrets-ad v0.5.3-0.20190814210122-0f2fd536b250 h1:+mm2cM5msg/USImbvnMS2yzCMBYMCO3CrvsATWGtHtY=
@@ -475,8 +487,8 @@ github.com/opencontainers/runc v0.1.1/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59P
github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=
github.com/openzipkin/zipkin-go v0.1.3/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=
github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw=
github.com/oracle/oci-go-sdk v5.15.0+incompatible h1:rTlmaWEe255HczQJ2uOPM9xw3prU9jNk5GxPy+RFi3k=
github.com/oracle/oci-go-sdk v5.15.0+incompatible/go.mod h1:VQb79nF8Z2cwLkLS35ukwStZIg5F66tcBccjip/j888=
github.com/oracle/oci-go-sdk v7.0.0+incompatible h1:oj5ESjXwwkFRdhZSnPlShvLWYdt/IZ65RQxveYM3maA=
github.com/oracle/oci-go-sdk v7.0.0+incompatible/go.mod h1:VQb79nF8Z2cwLkLS35ukwStZIg5F66tcBccjip/j888=
github.com/ory/dockertest v3.3.4+incompatible h1:VrpM6Gqg7CrPm3bL4Wm1skO+zFWLbh7/Xb5kGEbJRh8=
github.com/ory/dockertest v3.3.4+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs=
github.com/oxtoacart/bpool v0.0.0-20150712133111-4e1c5567d7c2 h1:CXwSGu/LYmbjEab5aMCs5usQRVBGThelUKBNnoSOuso=
@@ -489,6 +501,8 @@ github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaR
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
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/pierrec/lz4 v2.2.6+incompatible h1:6aCX4/YZ9v8q69hTyiR7dNLnTA3fgtKHVVW5BCd5Znw=
github.com/pierrec/lz4 v2.2.6+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
@@ -565,6 +579,8 @@ github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
@@ -638,6 +654,8 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2eP
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7 h1:fHDIZ2oxGnUZRN6WgWFCbYBjH9uqVPRCUVUDhs0wnbA=
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20181203162652-d668ce993890/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
@@ -677,6 +695,8 @@ golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190514135907-3a4b5fb9f71f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190523142557-0e01d883c5c5 h1:sM3evRHxE/1RuMe1FYAL3j7C7fUfIjkbE+NiDAYUF8U=
golang.org/x/sys v0.0.0-20190523142557-0e01d883c5c5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
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=
@@ -729,6 +749,8 @@ google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRn
google.golang.org/genproto v0.0.0-20190508193815-b515fa19cec8/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190513181449-d00d292a067c h1:m9avZ3wyOWBR0fLC+qWbMBulk+Jiiqelngssgp8jfIs=
google.golang.org/genproto v0.0.0-20190513181449-d00d292a067c/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64 h1:iKtrH9Y8mcbADOP0YFaEMth7OfuHY9xHOwNj4znpM1A=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.14.0 h1:ArxJuB1NWfPY6r9Gp9gqwplT0Ge7nqv9msgu03lHLmo=
google.golang.org/grpc v1.14.0/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
google.golang.org/grpc v1.16.0/go.mod h1:0JHn/cJsOMiMfNA9+DeHDlAU7KAAB5GDlYFpa9MZMio=

View File

@@ -31,6 +31,7 @@ require (
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 // indirect
golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e
golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db // indirect
google.golang.org/appengine v1.4.0 // indirect
google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107 // indirect
google.golang.org/grpc v1.22.0
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect

View File

@@ -57,6 +57,7 @@ import (
)
const secondInNanos = int64(time.Second / time.Nanosecond)
const maxSecondsInDuration = 315576000000
// Marshaler is a configurable object for converting between
// protocol buffer objects and a JSON representation for them.
@@ -182,7 +183,12 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU
return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
}
js["@type"] = (*json.RawMessage)(&turl)
if b, err = json.Marshal(js); err != nil {
if m.Indent != "" {
b, err = json.MarshalIndent(js, indent, m.Indent)
} else {
b, err = json.Marshal(js)
}
if err != nil {
return err
}
}
@@ -206,19 +212,26 @@ func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeU
// Any is a bit more involved.
return m.marshalAny(out, v, indent)
case "Duration":
// "Generated output always contains 0, 3, 6, or 9 fractional digits,
// depending on required precision."
s, ns := s.Field(0).Int(), s.Field(1).Int()
if s < -maxSecondsInDuration || s > maxSecondsInDuration {
return fmt.Errorf("seconds out of range %v", s)
}
if ns <= -secondInNanos || ns >= secondInNanos {
return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos)
}
if (s > 0 && ns < 0) || (s < 0 && ns > 0) {
return errors.New("signs of seconds and nanos do not match")
}
if s < 0 {
// Generated output always contains 0, 3, 6, or 9 fractional digits,
// depending on required precision, followed by the suffix "s".
f := "%d.%09d"
if ns < 0 {
ns = -ns
if s == 0 {
f = "-%d.%09d"
}
}
x := fmt.Sprintf("%d.%09d", s, ns)
x := fmt.Sprintf(f, s, ns)
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, ".000")

View File

@@ -38,7 +38,6 @@ package proto
import (
"fmt"
"log"
"os"
"reflect"
"sort"
"strconv"
@@ -194,7 +193,7 @@ func (p *Properties) Parse(s string) {
// "bytes,49,opt,name=foo,def=hello!"
fields := strings.Split(s, ",") // breaks def=, but handled below.
if len(fields) < 2 {
fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
log.Printf("proto: tag has too few fields: %q", s)
return
}
@@ -214,7 +213,7 @@ func (p *Properties) Parse(s string) {
p.WireType = WireBytes
// no numeric converter for non-numeric types
default:
fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
log.Printf("proto: tag has unknown wire type: %q", s)
return
}

View File

@@ -0,0 +1,9 @@
# 1.1.0 (May 22nd, 2019)
FEATURES
* Add `SeekLowerBound` to allow for range scans. [[GH-24](https://github.com/hashicorp/go-immutable-radix/pull/24)]
# 1.0.0 (August 30th, 2018)
* go mod adopted

View File

@@ -39,3 +39,28 @@ if string(m) != "foo" {
}
```
Here is an example of performing a range scan of the keys.
```go
// Create a tree
r := iradix.New()
r, _, _ = r.Insert([]byte("001"), 1)
r, _, _ = r.Insert([]byte("002"), 2)
r, _, _ = r.Insert([]byte("005"), 5)
r, _, _ = r.Insert([]byte("010"), 10)
r, _, _ = r.Insert([]byte("100"), 10)
// Range scan over the keys that sort lexicographically between [003, 050)
it := r.Root().Iterator()
it.SeekLowerBound([]byte("003"))
for key, _, ok := it.Next(); ok; key, _, ok = it.Next() {
if key >= "050" {
break
}
fmt.Println(key)
}
// Output:
// 005
// 010
```

View File

@@ -1,6 +1,8 @@
package iradix
import "bytes"
import (
"bytes"
)
// Iterator is used to iterate over a set of nodes
// in pre-order
@@ -53,6 +55,101 @@ func (i *Iterator) SeekPrefix(prefix []byte) {
i.SeekPrefixWatch(prefix)
}
func (i *Iterator) recurseMin(n *Node) *Node {
// Traverse to the minimum child
if n.leaf != nil {
return n
}
if len(n.edges) > 0 {
// Add all the other edges to the stack (the min node will be added as
// we recurse)
i.stack = append(i.stack, n.edges[1:])
return i.recurseMin(n.edges[0].node)
}
// Shouldn't be possible
return nil
}
// SeekLowerBound is used to seek the iterator to the smallest key that is
// greater or equal to the given key. There is no watch variant as it's hard to
// predict based on the radix structure which node(s) changes might affect the
// result.
func (i *Iterator) SeekLowerBound(key []byte) {
// Wipe the stack. Unlike Prefix iteration, we need to build the stack as we
// go because we need only a subset of edges of many nodes in the path to the
// leaf with the lower bound.
i.stack = []edges{}
n := i.node
search := key
found := func(n *Node) {
i.node = n
i.stack = append(i.stack, edges{edge{node: n}})
}
for {
// Compare current prefix with the search key's same-length prefix.
var prefixCmp int
if len(n.prefix) < len(search) {
prefixCmp = bytes.Compare(n.prefix, search[0:len(n.prefix)])
} else {
prefixCmp = bytes.Compare(n.prefix, search)
}
if prefixCmp > 0 {
// Prefix is larger, that means the lower bound is greater than the search
// and from now on we need to follow the minimum path to the smallest
// leaf under this subtree.
n = i.recurseMin(n)
if n != nil {
found(n)
}
return
}
if prefixCmp < 0 {
// Prefix is smaller than search prefix, that means there is no lower
// bound
i.node = nil
return
}
// Prefix is equal, we are still heading for an exact match. If this is a
// leaf we're done.
if n.leaf != nil {
if bytes.Compare(n.leaf.key, key) < 0 {
i.node = nil
return
}
found(n)
return
}
// Consume the search prefix
if len(n.prefix) > len(search) {
search = []byte{}
} else {
search = search[len(n.prefix):]
}
// Otherwise, take the lower bound next edge.
idx, lbNode := n.getLowerBoundEdge(search[0])
if lbNode == nil {
i.node = nil
return
}
// Create stack edges for the all strictly higher edges in this node.
if idx+1 < len(n.edges) {
i.stack = append(i.stack, n.edges[idx+1:])
}
i.node = lbNode
// Recurse
n = lbNode
}
}
// Next returns the next node in order
func (i *Iterator) Next() ([]byte, interface{}, bool) {
// Initialize our stack if needed

View File

@@ -79,6 +79,18 @@ func (n *Node) getEdge(label byte) (int, *Node) {
return -1, nil
}
func (n *Node) getLowerBoundEdge(label byte) (int, *Node) {
num := len(n.edges)
idx := sort.Search(num, func(i int) bool {
return n.edges[i].label >= label
})
// we want lower bound behavior so return even if it's not an exact match
if idx < num {
return idx, n.edges[idx].node
}
return -1, nil
}
func (n *Node) delEdge(label byte) {
num := len(n.edges)
idx := sort.Search(num, func(i int) bool {

View File

@@ -1 +1,3 @@
module github.com/hashicorp/golang-lru
go 1.12

View File

@@ -86,17 +86,35 @@ func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) {
}
// Remove removes the provided key from the cache.
func (c *Cache) Remove(key interface{}) {
func (c *Cache) Remove(key interface{}) (present bool) {
c.lock.Lock()
c.lru.Remove(key)
present = c.lru.Remove(key)
c.lock.Unlock()
return
}
// Resize changes the cache size.
func (c *Cache) Resize(size int) (evicted int) {
c.lock.Lock()
evicted = c.lru.Resize(size)
c.lock.Unlock()
return evicted
}
// RemoveOldest removes the oldest item from the cache.
func (c *Cache) RemoveOldest() {
func (c *Cache) RemoveOldest() (key interface{}, value interface{}, ok bool) {
c.lock.Lock()
c.lru.RemoveOldest()
key, value, ok = c.lru.RemoveOldest()
c.lock.Unlock()
return
}
// GetOldest returns the oldest entry
func (c *Cache) GetOldest() (key interface{}, value interface{}, ok bool) {
c.lock.Lock()
key, value, ok = c.lru.GetOldest()
c.lock.Unlock()
return
}
// Keys returns a slice of the keys in the cache, from oldest to newest.

View File

@@ -73,6 +73,9 @@ func (c *LRU) Add(key, value interface{}) (evicted bool) {
func (c *LRU) Get(key interface{}) (value interface{}, ok bool) {
if ent, ok := c.items[key]; ok {
c.evictList.MoveToFront(ent)
if ent.Value.(*entry) == nil {
return nil, false
}
return ent.Value.(*entry).value, true
}
return
@@ -142,6 +145,19 @@ func (c *LRU) Len() int {
return c.evictList.Len()
}
// Resize changes the cache size.
func (c *LRU) Resize(size int) (evicted int) {
diff := c.Len() - size
if diff < 0 {
diff = 0
}
for i := 0; i < diff; i++ {
c.removeOldest()
}
c.size = size
return diff
}
// removeOldest removes the oldest item from the cache.
func (c *LRU) removeOldest() {
ent := c.evictList.Back()

View File

@@ -10,7 +10,7 @@ type LRUCache interface {
// updates the "recently used"-ness of the key. #value, isFound
Get(key interface{}) (value interface{}, ok bool)
// Check if a key exsists in cache without updating the recent-ness.
// Checks if a key exists in cache without updating the recent-ness.
Contains(key interface{}) (ok bool)
// Returns key's value without updating the "recently used"-ness of the key.
@@ -31,6 +31,9 @@ type LRUCache interface {
// Returns the number of items in the cache.
Len() int
// Clear all cache entries
// Clears all cache entries.
Purge()
// Resizes cache, returning number evicted
Resize(int) int
}

View File

@@ -0,0 +1,4 @@
pkg/*
bin/*
.idea/*
vendor/*

View File

@@ -0,0 +1,363 @@
Mozilla Public License, version 2.0
1. Definitions
1.1. "Contributor"
means each individual or legal entity that creates, contributes to the
creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used by a
Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached the
notice in Exhibit A, the Executable Form of such Source Code Form, and
Modifications of such Source Code Form, in each case including portions
thereof.
1.5. "Incompatible With Secondary Licenses"
means
a. that the initial Contributor has attached the notice described in
Exhibit B to the Covered Software; or
b. that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the terms of
a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in a
separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible, whether
at the time of the initial grant or subsequently, any and all of the
rights conveyed by this License.
1.10. "Modifications"
means any of the following:
a. any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered Software; or
b. any new file in Source Code Form that contains any Covered Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the License,
by the making, using, selling, offering for sale, having made, import,
or transfer of either its Contributions or its Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU Lesser
General Public License, Version 2.1, the GNU Affero General Public
License, Version 3.0, or any later versions of those licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that controls, is
controlled by, or is under common control with You. For purposes of this
definition, "control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by contract or
otherwise, or (b) ownership of more than fifty percent (50%) of the
outstanding shares or beneficial ownership of such entity.
2. License Grants and Conditions
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
a. under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
b. under Patent Claims of such Contributor to make, use, sell, offer for
sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
a. for any code that a Contributor has removed from Covered Software; or
b. for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
c. under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights to
grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
Section 2.1.
3. Responsibilities
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
a. such Covered Software must also be made available in Source Code Form,
as described in Section 3.1, and You must inform recipients of the
Executable Form how they can obtain a copy of such Source Code Form by
reasonable means in a timely manner, at a charge no more than the cost
of distribution to the recipient; and
b. You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter the
recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty, or
limitations of liability) contained within the Source Code Form of the
Covered Software, except that You may alter any license notices to the
extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this License
with respect to some or all of the Covered Software due to statute,
judicial order, or regulation then You must: (a) comply with the terms of
this License to the maximum extent possible; and (b) describe the
limitations and the code they affect. Such description must be placed in a
text file included with all distributions of the Covered Software under
this License. Except to the extent prohibited by statute or regulation,
such description must be sufficiently detailed for a recipient of ordinary
skill to be able to understand it.
5. Termination
5.1. The rights granted under this License will terminate automatically if You
fail to comply with any of its terms. However, if You become compliant,
then the rights granted under this License from a particular Contributor
are reinstated (a) provisionally, unless and until such Contributor
explicitly and finally terminates Your grants, and (b) on an ongoing
basis, if such Contributor fails to notify You of the non-compliance by
some reasonable means prior to 60 days after You have come back into
compliance. Moreover, Your grants from a particular Contributor are
reinstated on an ongoing basis if such Contributor notifies You of the
non-compliance by some reasonable means, this is the first time You have
received notice of non-compliance with this License from such
Contributor, and You become compliant prior to 30 days after Your receipt
of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
license agreements (excluding distributors and resellers) which have been
validly granted by You or Your distributors under this License prior to
termination shall survive termination.
6. Disclaimer of Warranty
Covered Software is provided under this License on an "as is" basis,
without warranty of any kind, either expressed, implied, or statutory,
including, without limitation, warranties that the Covered Software is free
of defects, merchantable, fit for a particular purpose or non-infringing.
The entire risk as to the quality and performance of the Covered Software
is with You. Should any Covered Software prove defective in any respect,
You (not any Contributor) assume the cost of any necessary servicing,
repair, or correction. This disclaimer of warranty constitutes an essential
part of this License. No use of any Covered Software is authorized under
this License except under this disclaimer.
7. Limitation of Liability
Under no circumstances and under no legal theory, whether tort (including
negligence), contract, or otherwise, shall any Contributor, or anyone who
distributes Covered Software as permitted above, be liable to You for any
direct, indirect, special, incidental, or consequential damages of any
character including, without limitation, damages for lost profits, loss of
goodwill, work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses, even if such party shall have been
informed of the possibility of such damages. This limitation of liability
shall not apply to liability for death or personal injury resulting from
such party's negligence to the extent applicable law prohibits such
limitation. Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation may
not apply to You.
8. Litigation
Any litigation relating to this License may be brought only in the courts
of a jurisdiction where the defendant maintains its principal place of
business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions. Nothing
in this Section shall prevent a party's ability to bring cross-claims or
counter-claims.
9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides that
the language of a contract shall be construed against the drafter shall not
be used to construe this License against a Contributor.
10. Versions of the License
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses If You choose to distribute Source Code Form that is
Incompatible With Secondary Licenses under the terms of this version of
the License, the notice described in Exhibit B of this License must be
attached.
Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular file,
then You may include the notice in a location (such as a LICENSE file in a
relevant directory) where a recipient would be likely to look for such a
notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
This Source Code Form is "Incompatible
With Secondary Licenses", as defined by
the Mozilla Public License, v. 2.0.

View File

@@ -0,0 +1,62 @@
TOOL?=vault-plugin-auth-oci
TEST?=$$(go list ./... | grep -v /vendor/)
VETARGS?=-asmdecl -atomic -bool -buildtags -copylocks -methods -nilfunc -printf -rangeloops -shift -structtags -unsafeptr
EXTERNAL_TOOLS=\
github.com/mitchellh/gox \
github.com/golang/dep/cmd/dep
BUILD_TAGS?=${TOOL}
GOFMT_FILES?=$$(find . -name '*.go' | grep -v vendor)
# bin generates the releaseable binaries for this plugin
bin: fmtcheck generate
@CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' sh -c "'$(CURDIR)/scripts/build.sh'"
default: dev
# dev creates binaries for testing Vault locally. These are put
# into ./bin/ as well as $GOPATH/bin, except for quickdev which
# is only put into /bin/
quickdev: generate
@CGO_ENABLED=0 go build -i -tags='$(BUILD_TAGS)' -o bin/vault-plugin-auth-oci
dev: fmtcheck generate
@CGO_ENABLED=0 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'"
dev-dynamic: generate
@CGO_ENABLED=1 BUILD_TAGS='$(BUILD_TAGS)' VAULT_DEV_BUILD=1 sh -c "'$(CURDIR)/scripts/build.sh'"
# test runs the unit tests and vets the code
test: fmtcheck generate
CGO_ENABLED=0 VAULT_TOKEN= VAULT_ACC= go test -tags='$(BUILD_TAGS)' $(TEST) $(TESTARGS) -timeout=20m -parallel=4
testcompile: fmtcheck generate
@for pkg in $(TEST) ; do \
go test -v -c -tags='$(BUILD_TAGS)' $$pkg -parallel=4 ; \
done
# testacc runs acceptance tests
testacc: fmtcheck generate
@if [ "$(TEST)" = "./..." ]; then \
echo "ERROR: Set TEST to a specific package"; \
exit 1; \
fi
VAULT_ACC=1 go test -tags='$(BUILD_TAGS)' $(TEST) -v $(TESTARGS) -timeout 45m
# generate runs `go generate` to build the dynamically generated
# source files.
generate:
go generate $(go list ./... | grep -v /vendor/)
# bootstrap the build by downloading additional tools
bootstrap:
@for tool in $(EXTERNAL_TOOLS) ; do \
echo "Installing/Updating $$tool" ; \
go get -u $$tool; \
done
fmtcheck:
@sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'"
fmt:
gofmt -w $(GOFMT_FILES)
.PHONY: bin default generate test vet bootstrap fmt fmtcheck

View File

@@ -0,0 +1,2 @@
# Vault Plugin Auth OCI
Vault auth plugin for Oracle Cloud Infrastructure.

View File

@@ -0,0 +1,17 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import "github.com/oracle/oci-go-sdk/common"
// Do not edit this file. This is based on standard OCI GO SDK format
// Stores the request headers required for authenticating the client
type AuthenticateClientDetails struct {
RequestHeaders map[string][]string `json:"requestHeaders"`
}
// Prints the values of pointers in AuthenticateClientDetails,
// producing a human friendly string for an struct with pointers. Useful when debugging the values of a struct.
func (m AuthenticateClientDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,73 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// Do not edit this file. This is based on standard OCI GO SDK format
// Stores the request body and meta-data required for authenticating the client
type AuthenticateClientRequest struct {
// Request object for AuthenticateClientRequest
AuthenticateClientDetails `contributesTo:"body"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (e.g., if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
// Prints the values of pointers in AuthenticateClientRequest,
// producing a human friendly string for an struct with pointers. Useful when debugging the values of a struct.
func (request AuthenticateClientRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request AuthenticateClientRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request AuthenticateClientRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// Stores the response of the AuthenticateClient request, including meta-data.
type AuthenticateClientResponse struct {
// The underlying http response
RawResponse *http.Response
// The AuthenticateClientResult instance
AuthenticateClientResult `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
// particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
}
// Prints the values of pointers in AuthenticateClientResponse,
// producing a human friendly string for an struct with pointers. Useful when debugging the values of a struct.
func (response AuthenticateClientResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response AuthenticateClientResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,19 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import "github.com/oracle/oci-go-sdk/common"
// Do not edit this file. This is based on standard OCI GO SDK format
// Contains the result of the Authenticate Client request.
type AuthenticateClientResult struct {
Principal *Principal `json:"principal"`
ErrorMessage *string `json:"errorMessage"`
IsSuccess *bool `json:"success"`
}
// Prints the values of pointers in AuthenticateClientResult,
// producing a human friendly string for an struct with pointers. Useful when debugging the values of a struct.
func (m AuthenticateClientResult) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,156 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"context"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"net/http"
"os"
)
// Do not edit this file. This is based on standard OCI GO SDK format
// AuthenticationClient stores the client and configuration details for authenticating
type AuthenticationClient struct {
common.BaseClient
config *common.ConfigurationProvider
}
// NewAuthenticationClientWithConfigurationProvider Creates a new default Authentication client with the given configuration provider.
// the configuration provider will be used for the default signer as well as reading the region
func NewAuthenticationClientWithConfigurationProvider(configProvider common.ConfigurationProvider) (client AuthenticationClient, err error) {
baseClient, err := common.NewClientWithConfig(configProvider)
if err != nil {
return
}
client = AuthenticationClient{BaseClient: baseClient}
client.BasePath = ""
err = client.setConfigurationProvider(configProvider)
return
}
// SetRegion overrides the region of this client.
func (client *AuthenticationClient) SetHost(host string) {
client.Host = host
}
// SetConfigurationProvider sets the configuration provider including the region, returns an error if is not valid
func (client *AuthenticationClient) setConfigurationProvider(configProvider common.ConfigurationProvider) error {
if ok, err := common.IsConfigurationProviderValid(configProvider); !ok {
return err
}
// Error has been checked already
region, _ := configProvider.Region()
client.config = &configProvider
if regionURL, ok := os.LookupEnv("OCI_SDK_AUTH_CLIENT_REGION_URL"); ok {
client.Host = regionURL
} else {
client.Host = fmt.Sprintf(common.DefaultHostURLTemplate, "auth", string(region))
}
client.BasePath = "/v1"
return nil
}
// SetRegion overrides the region of this client.
func (client *AuthenticationClient) SetRegion(region string) {
client.Host = fmt.Sprintf(common.DefaultHostURLTemplate, "auth", region)
}
// AuthenticateClient takes in a request to authenticate a client, makes the API request to OCI Identity and returns the Response.
// If the authentication is successful, the AuthenticateClientResult member of the response will contain the Principal of the authenticated entity.
func (client AuthenticationClient) AuthenticateClient(ctx context.Context, request AuthenticateClientRequest) (response AuthenticateClientResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.authenticateClient, policy)
if err != nil {
if ociResponse != nil {
response = AuthenticateClientResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(AuthenticateClientResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into AuthenticateClientResponse")
}
return
}
func (client AuthenticationClient) authenticateClient(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/authentication/authenticateClient")
if err != nil {
return nil, err
}
var response AuthenticateClientResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// FilterGroupMembership takes in a list of Group or Dynamic Group IDs and a Principal context and makes an API request to OCI Identity.
// If the request is successful, it returns the subset of the request groups that the entity corresponding to the Principal is a part of.
func (client AuthenticationClient) FilterGroupMembership(ctx context.Context, request FilterGroupMembershipRequest) (response FilterGroupMembershipResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.filterGroupMembership, policy)
if err != nil {
if ociResponse != nil {
response = FilterGroupMembershipResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(FilterGroupMembershipResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into FilterGroupMembershipResponse")
}
return
}
func (client AuthenticationClient) filterGroupMembership(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/filterGroupMembership")
if err != nil {
return nil, err
}
var response FilterGroupMembershipResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}

View File

@@ -0,0 +1,95 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"context"
"fmt"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"github.com/oracle/oci-go-sdk/common/auth"
"sync"
)
func Factory(ctx context.Context, conf *logical.BackendConfig) (logical.Backend, error) {
b, err := Backend()
if err != nil {
return nil, err
}
if err := b.Setup(ctx, conf); err != nil {
return nil, err
}
return b, nil
}
type backend struct {
*framework.Backend
// Lock to make changes to authClient entries
authClientMutex sync.RWMutex
// The client used to authenticate with OCI Identity
authenticationClient *AuthenticationClient
}
func Backend() (*backend, error) {
b := &backend{}
b.Backend = &framework.Backend{
Help: backendHelp,
PathsSpecial: &logical.Paths{
Unauthenticated: []string{
"login/*",
},
},
Paths: []*framework.Path{
pathLogin(b),
pathRole(b),
pathListRoles(b),
pathConfig(b),
},
BackendType: logical.TypeCredential,
}
return b, nil
}
// createAuthClient creates an authentication client if one was not already created and stores in the backend.
func (b *backend) createAuthClient() error {
b.authClientMutex.Lock()
defer b.authClientMutex.Unlock()
if b.authenticationClient != nil {
return nil
}
// Create the instance principal provider
ip, err := auth.InstancePrincipalConfigurationProvider()
if err != nil {
b.Logger().Debug("Unable to create InstancePrincipalConfigurationProvider", "err", err)
return fmt.Errorf("unable to create InstancePrincipalConfigurationProvider")
}
// Create the authentication client
authenticationClient, err := NewAuthenticationClientWithConfigurationProvider(ip)
if err != nil {
b.Logger().Debug("Unable to create authenticationClient", "err", err)
return fmt.Errorf("unable to create authenticationClient")
}
b.authenticationClient = &authenticationClient
return nil
}
const backendHelp = `
The OCI Auth plugin enables authentication and authorization using OCI Identity credentials.
The OCI Auth plugin authorizes using roles. A role is defined as a set of allowed policies for specific entities.
When an entity such as a user or instance logs in, it requests a role.
The OCI Auth plugin checks whether the entity is allowed to use the role and which policies are associated with that role.
It then assigns the given policies to the request.
The goal of roles is to restrict access to only the subset of secrets that are required,
even if the entity has access to many more secrets. This conforms to the least-privilege security model.
`

View File

@@ -0,0 +1,147 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"fmt"
"strings"
"github.com/hashicorp/vault/api"
"github.com/oracle/oci-go-sdk/common"
"github.com/oracle/oci-go-sdk/common/auth"
"net/http"
"net/url"
)
type CLIHandler struct{}
func (h *CLIHandler) Help() string {
help := `
Usage: vault login -method=oci auth_type=apikey
vault login -method=oci auth_type=instance
The OCI auth method allows users to authenticate with OCI
credentials. The OCI credentials may be specified in a number of ways,
listed below:
1. API Key
2. Instance Principal
Authenticate using API key:
First create a configuration file as explained in https://docs.us-phoenix-1.oraclecloud.com/Content/API/Concepts/sdkconfig.htm
Then login using the following command:
$ vault login -method=oci auth_type=apikey role=<RoleName>
Authenticate using Instance Principal:
https://docs.cloud.oracle.com/iaas/Content/Identity/Tasks/callingservicesfrominstances.htm
$ vault login -method=oci auth_type=instance role=<RoleName>
Configuration:
auth_type=<string>
Enter one of following:
apikey (or) ak
instance (or) ip
`
return strings.TrimSpace(help)
}
func (h *CLIHandler) Auth(c *api.Client, m map[string]string) (*api.Secret, error) {
role, ok := m["role"]
if !ok {
return nil, fmt.Errorf("Enter the role")
}
role = strings.ToLower(role)
path := fmt.Sprintf(PathBaseFormat, role)
signingPath := PathVersionBase + path
loginData, err := CreateLoginData(c.Address(), m, signingPath)
if err != nil {
return nil, err
}
// Now try to login
secret, err := c.Logical().Write(path, loginData)
if err != nil {
return nil, err
}
return secret, nil
}
// CreateLoginData creates the interface required for a login request, signed using the corresponding OCI Identity Principal
func CreateLoginData(clientAddress string, m map[string]string, path string) (map[string]interface{}, error) {
authtype, ok := m["auth_type"]
if !ok {
return nil, fmt.Errorf("Enter the auth_type")
}
switch strings.ToLower(authtype) {
case "ip", "instance":
return createLoginDataForInstancePrincipal(clientAddress, path)
case "ak", "apikey":
return createLoginDataForApiKeys(clientAddress, path)
}
return nil, fmt.Errorf("Unknown auth_type")
}
func createLoginDataForApiKeys(clientAddress string, path string) (map[string]interface{}, error) {
provider := common.DefaultConfigProvider()
ociClient, err := NewOciClientWithConfigurationProvider(provider)
if err != nil {
return nil, err
}
return createFinalLoginData(clientAddress, &ociClient, path)
}
func createLoginDataForInstancePrincipal(clientAddress string, path string) (map[string]interface{}, error) {
ip, err := auth.InstancePrincipalConfigurationProvider()
if err != nil {
return nil, err
}
ociClient, err := NewOciClientWithConfigurationProvider(ip)
if err != nil {
return nil, err
}
return createFinalLoginData(clientAddress, &ociClient, path)
}
func createFinalLoginData(clientAddress string, ociClient *OciClient, path string) (map[string]interface{}, error) {
ociClient.Host = clientAddress
request, err := ociClient.ConstructLoginRequest(path)
if err != nil {
return nil, err
}
clientURL, err := url.Parse(clientAddress)
if err != nil {
return nil, err
}
request.Host = clientURL.Host
// serialize the request
serializedRequest := serializeRequest(request)
// pack it into loginData
loginData := make(map[string]interface{})
loginData["request_headers"] = serializedRequest
return loginData, nil
}
func serializeRequest(request http.Request) map[string][]string {
requestHeaders := request.Header
requestHeaders["host"] = []string{request.Host}
requestHeaders["(request-target)"] = []string{getRequestTarget(&request)}
return requestHeaders
}

View File

@@ -0,0 +1,18 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import "github.com/oracle/oci-go-sdk/common"
// Do not edit this file. This is based on standard OCI GO SDK format
// Stores the Principal and list of Group or Dynamic Group Ids required for the filtering request
type FilterGroupMembershipDetails struct {
Principal Principal `json:"principal"`
GroupIds []string `json:"groupIds"`
}
// Prints the values of pointers in FilterGroupMembershipDetails,
// producing a human friendly string for an struct with pointers. Useful when debugging the values of a struct.
func (m FilterGroupMembershipDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,71 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// Do not edit this file. This is based on standard OCI GO SDK format
// Stores the request body and meta-data required for filtering the group membership
type FilterGroupMembershipRequest struct {
// Request object for FilterGroupMembershipRequest
FilterGroupMembershipDetails `contributesTo:"body"`
// A token that uniquely identifies a request so it can be retried in case of a timeout or
// server error without risk of executing that same action again. Retry tokens expire after 24
// hours, but can be invalidated before then due to conflicting operations (e.g., if a resource
// has been deleted and purged from the system, then a retry of the original creation request
// may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request FilterGroupMembershipRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request FilterGroupMembershipRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request FilterGroupMembershipRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// Stores the response of the FilterGroupMembership request, including meta-data.
type FilterGroupMembershipResponse struct {
// The underlying http response
RawResponse *http.Response
// The FilterGroupMembershipResult instance
FilterGroupMembershipResult `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
// particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
}
func (response FilterGroupMembershipResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response FilterGroupMembershipResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,18 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import "github.com/oracle/oci-go-sdk/common"
// Do not edit this file. This is based on standard OCI GO SDK format
// Contains the result of the FilterGroupMembership request.
type FilterGroupMembershipResult struct {
Principal Principal `json:"principal"`
GroupIds []string `json:"groupIds"`
}
// Prints the values of pointers in FilterGroupMembershipResult,
// producing a human friendly string for an struct with pointers. Useful when debugging the values of a struct.
func (m FilterGroupMembershipResult) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,26 @@
module github.com/hashicorp/vault-plugin-auth-oci
go 1.12
require (
github.com/armon/go-radix v1.0.0 // indirect
github.com/frankban/quicktest v1.4.1 // indirect
github.com/go-test/deep v1.0.2 // indirect
github.com/google/go-cmp v0.3.1 // indirect
github.com/hashicorp/errwrap v1.0.0
github.com/hashicorp/go-hclog v0.9.2
github.com/hashicorp/go-immutable-radix v1.1.0 // indirect
github.com/hashicorp/go-version v1.2.0 // indirect
github.com/hashicorp/golang-lru v0.5.3 // indirect
github.com/hashicorp/vault/api v1.0.4
github.com/hashicorp/vault/sdk v0.1.13
github.com/oracle/oci-go-sdk v7.0.0+incompatible
github.com/pierrec/lz4 v2.2.6+incompatible // indirect
github.com/pkg/errors v0.8.1
github.com/stretchr/objx v0.2.0 // indirect
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 // indirect
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7 // indirect
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a // indirect
golang.org/x/text v0.3.2 // indirect
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64 // indirect
)

View File

@@ -0,0 +1,186 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI=
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
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/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/frankban/quicktest v1.4.1 h1:Wv2VwvNn73pAdFIVUQRXYDFp31lXKbqblIXo/Q5GPSg=
github.com/frankban/quicktest v1.4.1/go.mod h1:36zfPVQyHxymz4cH7wlDmVwDrJuljRB60qkgn7rorfQ=
github.com/go-ldap/ldap v3.0.2+incompatible/go.mod h1:qfd9rJvER9Q0/D/Sqn1DfHRoBp40uXYvFoEVrNEPqRc=
github.com/go-test/deep v1.0.2-0.20181118220953-042da051cf31 h1:28FVBuwkwowZMjbA7M0wXsI6t3PYulRTMio3SO+eKCM=
github.com/go-test/deep v1.0.2-0.20181118220953-042da051cf31/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/go-test/deep v1.0.2 h1:onZX1rnHT3Wv6cqNgYyFOOlgVKJrksuCMCRvJStbMYw=
github.com/go-test/deep v1.0.2/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
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 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=
github.com/hashicorp/errwrap v1.0.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 h1:z3ollgGRg8RjfJH6UVBaG54R70GFd++QOkvnJH3VSBY=
github.com/hashicorp/go-hclog v0.8.0/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
github.com/hashicorp/go-hclog v0.9.2 h1:CG6TE5H9/JXsFWJCfoIVpKFIkFe6ysEuHirp4DxCsHI=
github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
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-immutable-radix v1.1.0 h1:vN9wG1D6KG6YHRTWr8512cxGOVgTMEfgEdSj/hr8MPc=
github.com/hashicorp/go-immutable-radix v1.1.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-plugin v1.0.1 h1:4OtAfUGbnKC6yS48p0CtMX2oFYtzFZVv6rok3cRWgnE=
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 h1:DMo4fmknnz0E0evoNYnV48RjWndOsmd6OW+09R3cEP8=
github.com/hashicorp/go-rootcerts v1.0.1/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=
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-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 h1:bPIoEKD27tNdebFGGxxYwcL4nepeY4j1QP23PFRGzg0=
github.com/hashicorp/go-version v1.1.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/go-version v1.2.0 h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E=
github.com/hashicorp/go-version v1.2.0/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 h1:0hERBMJE1eitiLkihrMvRVBYAkpHzc/J3QdDN+dAcgU=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.3 h1:YPkqC67at8FYaadspW/6uE0COsBxS2656RLEr8Bppgk=
github.com/hashicorp/golang-lru v0.5.3/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/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 h1:kJCB4vdITiW1eC1vq2e6IsrXKrZit1bv/TDYFGMp4BQ=
github.com/hashicorp/yamux v0.0.0-20181012175058-2f1d1f20f75d/go.mod h1:+NfK9FKeTrX5uv1uIXGdwYDTeHna2qgaIlx54MXqjAM=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
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 v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/oklog/run v1.0.0 h1:Ru7dDtJNOyC66gQ5dQmaCa0qIsAUFY3sFpK1Xk8igrw=
github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA=
github.com/oracle/oci-go-sdk v7.0.0+incompatible h1:oj5ESjXwwkFRdhZSnPlShvLWYdt/IZ65RQxveYM3maA=
github.com/oracle/oci-go-sdk v7.0.0+incompatible/go.mod h1:VQb79nF8Z2cwLkLS35ukwStZIg5F66tcBccjip/j888=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
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/pierrec/lz4 v2.2.6+incompatible h1:6aCX4/YZ9v8q69hTyiR7dNLnTA3fgtKHVVW5BCd5Znw=
github.com/pierrec/lz4 v2.2.6+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.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/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/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc=
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
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-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
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-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-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7 h1:fHDIZ2oxGnUZRN6WgWFCbYBjH9uqVPRCUVUDhs0wnbA=
golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
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 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/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-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-20190403152447-81d4e9dc473e h1:nFYrTHrdrAOpShe27kaFHjsqYSEQ0KWqdWLu3xuZJts=
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-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ=
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db h1:6/JqlYfC1CCaLnGceQTI+sDGhC9UBSPAsBqI0Gun6kU=
golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107 h1:xtNn7qFlagY2mQNFHMSRPjT2RkOV4OXM7P5TVy9xATo=
google.golang.org/genproto v0.0.0-20190404172233-64821d5d2107/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64 h1:iKtrH9Y8mcbADOP0YFaEMth7OfuHY9xHOwNj4znpM1A=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
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.22.0 h1:J0UbZOIrCAl+fpTOf8YLs4dJo8L/owV4LYVtAXQoPkw=
google.golang.org/grpc v1.22.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.23.0 h1:AzbTB6ux+okLTzP8Ru1Xs41C303zdcfEht7MQnYJt5A=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d/go.mod h1:cuepJuh7vyXfUyUwEgHQXw849cJrilpS5NeIjOWESAw=
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=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@@ -0,0 +1,62 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
// Do not edit this file. This is based on standard OCI GO SDK format
// Claim is a representation of a JWT claim
type InternalClaim struct {
Issuer string `json:"issuer"`
Key string `json:"key"`
Value string `json:"value"`
}
// These constants define types of principal
const (
PrincipalTypeUser = "user"
PrincipalTypeInstance = "instance"
)
// This constant defines the Principal type key
var (
ClaimPrincipalType = "ptype"
)
// Claims represents a collection of JWT claims
type InternalClaims map[string][]InternalClaim
// FromClaims takes in a list of claims and coverts it to InternalClaims
func FromClaims(claimList []Claim) InternalClaims {
outputMap := make(map[string][]InternalClaim)
for _, item := range claimList {
internalClaim := FromClaim(item)
outputMap[internalClaim.Key] = append(outputMap[internalClaim.Key], internalClaim)
}
return outputMap
}
// FromClaims takes in a claim and coverts it to an InternalClaim
func FromClaim(claim Claim) InternalClaim {
return InternalClaim{
Issuer: *claim.Issuer,
Key: *claim.Key,
Value: *claim.Value,
}
}
// GetSingleClaim returns single claim given a claim type.
func (c InternalClaims) GetSingleClaim(key string) InternalClaim {
claims := c[key]
if len(claims) > 0 {
return claims[0]
}
return InternalClaim{}
}
// GetString returns the claim value given a claim type.
func (c InternalClaims) GetString(key string) string {
claim := c.GetSingleClaim(key)
return claim.Value
}

View File

@@ -0,0 +1,113 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"errors"
"fmt"
"github.com/hashicorp/errwrap"
"github.com/oracle/oci-go-sdk/common"
"net/http"
"net/url"
"path"
"strings"
"time"
)
// OciClient stores the client and configuration details for making API requests to OCI Identity Service
type OciClient struct {
common.BaseClient
config *common.ConfigurationProvider
}
// These constants store information related to signing the http request
const (
// requestHeaderDate The key for passing a header to indicate Date
requestHeaderDate = "Date"
// requestHeaderUserAgent The key for passing a header to indicate User Agent
requestHeaderUserAgent = "User-Agent"
defaultScheme = "https"
)
// NewIdentityClientWithConfigurationProvider Creates a new default Identity client with the given configuration provider.
// the configuration provider will be used for the default signer as well as reading the region
func NewOciClientWithConfigurationProvider(configProvider common.ConfigurationProvider) (client OciClient, err error) {
baseClient, err := common.NewClientWithConfig(configProvider)
if err != nil {
return client, err
}
client = OciClient{BaseClient: baseClient}
err = client.setConfigurationProvider(configProvider)
return client, err
}
// SetConfigurationProvider sets the configuration provider including the region, returns an error if is not valid
func (client *OciClient) setConfigurationProvider(configProvider common.ConfigurationProvider) error {
if ok, err := common.IsConfigurationProviderValid(configProvider); !ok {
return err
}
// Error has been checked already
client.config = &configProvider
return nil
}
// ConstructLoginRequest takes in a path and returns a signed http request
func (client OciClient) ConstructLoginRequest(path string) (request http.Request, err error) {
httpRequest, err := common.MakeDefaultHTTPRequestWithTaggedStruct(http.MethodGet, path, request)
if err != nil {
return
}
err = client.prepareRequest(&httpRequest)
if err != nil {
return
}
err = client.Signer.Sign(&httpRequest)
if err != nil {
return
}
request = httpRequest
return
}
// prepareRequest takes in a http request and adds the required information for signing it
func (client *OciClient) prepareRequest(request *http.Request) (err error) {
if client.UserAgent == "" {
return errors.New("user agent can not be blank")
}
if request.Header == nil {
request.Header = http.Header{}
}
request.Header.Set(requestHeaderUserAgent, client.UserAgent)
request.Header.Set(requestHeaderDate, time.Now().UTC().Format(http.TimeFormat))
if !strings.HasPrefix(client.Host, "http://") &&
!strings.HasPrefix(client.Host, "https://") {
client.Host = fmt.Sprintf("%s://%s", defaultScheme, client.Host)
}
clientURL, err := url.Parse(client.Host)
if err != nil {
return errwrap.Wrapf("host is invalid. {{err}}", err)
}
request.URL.Host = clientURL.Host
request.URL.Scheme = clientURL.Scheme
currentPath := request.URL.Path
if !strings.Contains(currentPath, fmt.Sprintf("/%s", client.BasePath)) {
request.URL.Path = path.Clean(fmt.Sprintf("/%s/%s", client.BasePath, currentPath))
}
return
}
// getRequestTarget returns the value of the special (request-target) header field name
// per https://tools.ietf.org/html/draft-cavage-http-signatures-06#section-2.3
func getRequestTarget(request *http.Request) string {
lowercaseMethod := strings.ToLower(request.Method)
return fmt.Sprintf("%s %s", lowercaseMethod, request.URL.RequestURI())
}

View File

@@ -0,0 +1,158 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"context"
"fmt"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"strings"
)
// These constants store the configuration keys
const (
HomeTenancyIdConfigName = "home_tenancy_id"
)
func pathConfig(b *backend) *framework.Path {
return &framework.Path{
Pattern: "config",
Fields: map[string]*framework.FieldSchema{
HomeTenancyIdConfigName: {
Type: framework.TypeString,
Description: "The tenancy id of the account.",
},
},
ExistenceCheck: b.pathConfigExistenceCheck,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.CreateOperation: b.pathConfigCreateUpdate,
logical.UpdateOperation: b.pathConfigCreateUpdate,
logical.DeleteOperation: b.pathConfigDelete,
logical.ReadOperation: b.pathConfigRead,
},
HelpSynopsis: pathConfigSyn,
HelpDescription: pathConfigDesc,
}
}
// Establishes dichotomy of request operation between CreateOperation and UpdateOperation.
// Returning 'true' forces an UpdateOperation, CreateOperation otherwise.
func (b *backend) pathConfigExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
entry, err := b.getOCIConfig(ctx, req.Storage)
if err != nil {
return false, err
}
return entry != nil, nil
}
// setOCIConfig creates or updates a config in the storage.
func (b *backend) setOCIConfig(ctx context.Context, s logical.Storage, configEntry *OCIConfigEntry) error {
if configEntry == nil {
return fmt.Errorf("config is not found")
}
entry, err := logical.StorageEntryJSON("config", configEntry)
if err != nil {
return err
}
if err := s.Put(ctx, entry); err != nil {
return err
}
return nil
}
// getOCIConfig returns the properties set on the given config.
// This method also does NOT check to see if a config upgrade is required. It is
// the responsibility of the caller to check if a config upgrade is required and,
// if so, to upgrade the config
func (b *backend) getOCIConfig(ctx context.Context, s logical.Storage) (*OCIConfigEntry, error) {
entry, err := s.Get(ctx, "config")
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var result OCIConfigEntry
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
}
return &result, nil
}
func (b *backend) pathConfigRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
configEntry, err := b.getOCIConfig(ctx, req.Storage)
if err != nil {
return nil, err
}
if configEntry == nil {
return nil, nil
}
responseData := map[string]interface{}{
HomeTenancyIdConfigName: configEntry.HomeTenancyId,
}
return &logical.Response{
Data: responseData,
}, nil
}
// Create a Config
func (b *backend) pathConfigCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
homeTenancyId := data.Get(HomeTenancyIdConfigName).(string)
if strings.TrimSpace(homeTenancyId) == "" {
return logical.ErrorResponse("Missing homeTenancyId"), nil
}
configEntry, err := b.getOCIConfig(ctx, req.Storage)
if err != nil {
return nil, err
}
if configEntry == nil && req.Operation == logical.UpdateOperation {
return logical.ErrorResponse("The specified config does not exist"), nil
}
configEntry = &OCIConfigEntry{
HomeTenancyId: homeTenancyId,
}
if err := b.setOCIConfig(ctx, req.Storage, configEntry); err != nil {
return nil, err
}
var resp logical.Response
return &resp, nil
}
// Delete a Config
func (b *backend) pathConfigDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
return nil, req.Storage.Delete(ctx, "config")
}
// Struct to hold the information associated with an OCI config
type OCIConfigEntry struct {
HomeTenancyId string `json:"home_tenancy_id" `
}
const pathConfigSyn = `
Manages the configuration for the Vault Auth Plugin.
`
const pathConfigDesc = `
The home_tenancy_id configuration is the Tenant OCID of your OCI Account. Only login requests from entities present in this tenant are accepted.
Example:
vault write /auth/oci/config home_tenancy_id=myocid
`

View File

@@ -0,0 +1,233 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"context"
"fmt"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"github.com/oracle/oci-go-sdk/common"
"github.com/pkg/errors"
"net/http"
"strings"
"unicode"
)
// These constants store the required http path & method information for validating the signed request
const (
PathVersionBase = "/v1"
PathBaseFormat = "/auth/oci/login/%s"
PathLoginMethod = "get"
)
// Signing Header constants
const (
// HdrRequestTarget represents the special header name used to refer to the HTTP verb and URI in the signature.
HdrRequestTarget = `(request-target)`
)
func pathLogin(b *backend) *framework.Path {
return &framework.Path{
Pattern: "login/" + framework.GenericNameRegex("role"),
Fields: map[string]*framework.FieldSchema{
"request_headers": {
Type: framework.TypeHeader,
Description: `The signed headers of the client`,
},
"role": {
Type: framework.TypeLowerCaseString,
Description: "Name of the role.",
},
},
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.UpdateOperation: b.pathLoginUpdate,
},
HelpSynopsis: pathLoginSyn,
HelpDescription: pathLoginDesc,
}
}
func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
// Validate the role
role, ok := data.GetOk("role")
if !ok {
return logical.ErrorResponse("Role is not specified"), nil
}
roleName := role.(string)
b.Logger().Trace(req.ID, "pathLoginUpdate roleName", roleName)
// Validate that the role exists
roleEntry, err := b.getOCIRole(ctx, req.Storage, roleName)
if err != nil {
return unauthorizedLogicalResponse(req, b.Logger(), err)
}
if roleEntry == nil {
return unauthorizedLogicalResponse(req, b.Logger(), fmt.Errorf("Role is not found"))
}
// Parse the authentication headers
requestHeaders := data.Get("request_headers")
if !ok {
return logical.ErrorResponse("request_headers is not specified"), nil
}
authenticateRequestHeaders := requestHeaders.(http.Header)
// Find the targetUrl and Method
finalLoginPath := PathVersionBase + fmt.Sprintf(PathBaseFormat, roleName)
method, targetUrl, err := requestTargetToMethodURL(authenticateRequestHeaders[HdrRequestTarget], PathLoginMethod, finalLoginPath)
if err != nil {
return unauthorizedLogicalResponse(req, b.Logger(), err)
}
b.Logger().Trace(req.ID, "Method:", method, "targetUrl:", targetUrl)
authenticateClientDetails := AuthenticateClientDetails{
RequestHeaders: authenticateRequestHeaders,
}
requestMetadata := common.RequestMetadata{
nil,
}
authenticateClientRequest := AuthenticateClientRequest{
authenticateClientDetails,
nil,
&req.ID,
requestMetadata,
}
// Authenticate the request with Identity
if b.authenticationClient == nil && b.createAuthClient() != nil {
return logical.RespondWithStatusCode(nil, req, http.StatusInternalServerError)
}
authenticateClientResponse, err := b.authenticationClient.AuthenticateClient(ctx, authenticateClientRequest)
if err != nil {
return unauthorizedLogicalResponse(req, b.Logger(), err)
}
if authenticateClientResponse.Principal == nil ||
len(authenticateClientResponse.Principal.Claims) == 0 ||
*authenticateClientResponse.IsSuccess == false {
return unauthorizedLogicalResponse(req, b.Logger(), err)
}
internalClaims := FromClaims(authenticateClientResponse.Principal.Claims)
principalType := internalClaims.GetString(ClaimPrincipalType)
// Check the principal type
if principalType != PrincipalTypeInstance && principalType != PrincipalTypeUser {
return unauthorizedLogicalResponse(req, b.Logger(), err)
}
b.Logger().Trace("Authentication ok", "Method:", method, "targetUrl:", targetUrl, "id", req.ID)
// Validate the home tenancy
err = b.validateHomeTenancy(ctx, req, *authenticateClientResponse.Principal.TenantId)
if err != nil {
return unauthorizedLogicalResponse(req, b.Logger(), err)
}
// Find whether the entity corresponding the Principal is a part of any OCIDs allowed to take the role
filterGroupMembershipDetails := FilterGroupMembershipDetails{
*authenticateClientResponse.Principal,
roleEntry.OcidList,
}
filterGroupMembershipRequest := FilterGroupMembershipRequest{
filterGroupMembershipDetails,
nil,
&req.ID,
requestMetadata,
}
filterGroupMembershipResponse, err := b.authenticationClient.FilterGroupMembership(ctx, filterGroupMembershipRequest)
if err != nil {
return unauthorizedLogicalResponse(req, b.Logger(), err)
}
if filterGroupMembershipResponse.GroupIds == nil {
return unauthorizedLogicalResponse(req, b.Logger(), err)
}
// Validate that the filtered list contains atleast one of the OCIDs of the Role
filteredOcidMap := sliceToMap(filterGroupMembershipResponse.GroupIds)
found := false
for _, item := range roleEntry.OcidList {
_, present := filteredOcidMap[item]
if present {
found = true
break
}
}
if found == false {
return unauthorizedLogicalResponse(req, b.Logger(), fmt.Errorf("Entity not a part of any of the Role OCIDs"))
}
b.Logger().Trace("Login ok", "Method:", method, "targetUrl:", targetUrl, "id", req.ID)
// Return the response
auth := &logical.Auth{
Metadata: map[string]string{
"role_name": roleName,
},
InternalData: map[string]interface{}{
"role_name": roleName,
},
DisplayName: roleName,
Alias: &logical.Alias{
Name: "name",
},
}
roleEntry.PopulateTokenAuth(auth)
auth.Renewable = false
resp := &logical.Response{
Auth: auth,
}
return resp, nil
}
func (b *backend) validateHomeTenancy(ctx context.Context, req *logical.Request, homeTenancyId string) error {
configEntry, err := b.getOCIConfig(ctx, req.Storage)
if err != nil {
return err
}
if configEntry == nil || configEntry.HomeTenancyId == "" {
return fmt.Errorf("Home Tenancy is invalid")
}
if homeTenancyId != configEntry.HomeTenancyId {
return fmt.Errorf("Invalid Tenancy")
}
return nil
}
func unauthorizedLogicalResponse(req *logical.Request, logger log.Logger, err error) (*logical.Response, error) {
logger.Trace(req.ID, ": Failed with error:", err)
return logical.RespondWithStatusCode(nil, req, http.StatusUnauthorized)
}
func requestTargetToMethodURL(requestTarget []string, expectedMethod string, expectedUrl string) (method string, url string, err error) {
if len(requestTarget) == 0 {
return "", "", errors.New("no (request-target) specified in header")
}
parts := strings.FieldsFunc(requestTarget[0], unicode.IsSpace)
if len(parts) != 2 || strings.ToLower(parts[0]) != expectedMethod || strings.ToLower(parts[1]) != expectedUrl {
return "", "", errors.New("incorrect (request-target) specified in header")
}
return parts[0], parts[1], nil
}
const pathLoginSyn = `
Authenticates to Vault using OCI credentials
`
const pathLoginDesc = `
Authenticates to Vault using OCI credentials such as User Api Key, Instance Principal
`

View File

@@ -0,0 +1,213 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import (
"context"
"fmt"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/tokenutil"
"github.com/hashicorp/vault/sdk/logical"
)
// Constants for role specific data
const (
// Increasing this above this limit might require implementing
// client-side paging in the filterGroupMembership API
MaxOCIDsPerRole = 100
)
func pathRole(b *backend) *framework.Path {
p := &framework.Path{
Pattern: "role/" + framework.GenericNameRegex("role"),
Fields: map[string]*framework.FieldSchema{
"role": {
Type: framework.TypeLowerCaseString,
Description: "Name of the role.",
},
"ocid_list": {
Type: framework.TypeCommaStringSlice,
Description: `A comma separated list of Group or Dynamic Group OCIDs that are allowed to take this role.`,
},
},
ExistenceCheck: b.pathRoleExistenceCheck,
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.CreateOperation: b.pathRoleCreateUpdate,
logical.UpdateOperation: b.pathRoleCreateUpdate,
logical.ReadOperation: b.pathRoleRead,
logical.DeleteOperation: b.pathRoleDelete,
},
HelpSynopsis: pathRoleSyn,
HelpDescription: pathRoleDesc,
}
tokenutil.AddTokenFields(p.Fields)
return p
}
func pathListRoles(b *backend) *framework.Path {
return &framework.Path{
Pattern: "role/?",
Callbacks: map[logical.Operation]framework.OperationFunc{
logical.ListOperation: b.pathRoleList,
},
HelpSynopsis: pathListRolesHelpSyn,
HelpDescription: pathListRolesHelpDesc,
}
}
// Establishes dichotomy of request operation between CreateOperation and UpdateOperation.
// Returning 'true' forces an UpdateOperation, CreateOperation otherwise.
func (b *backend) pathRoleExistenceCheck(ctx context.Context, req *logical.Request, data *framework.FieldData) (bool, error) {
entry, err := b.getOCIRole(ctx, req.Storage, data.Get("role").(string))
if err != nil {
return false, err
}
return entry != nil, nil
}
// setOciRole creates or updates a role in the storage.
func (b *backend) setOCIRole(ctx context.Context, s logical.Storage, roleName string,
roleEntry *OCIRoleEntry) error {
if roleName == "" {
return fmt.Errorf("missing role name")
}
if roleEntry == nil {
return fmt.Errorf("nil role entry")
}
entry, err := logical.StorageEntryJSON("role/"+roleName, roleEntry)
if err != nil {
return err
}
if err := s.Put(ctx, entry); err != nil {
return err
}
return nil
}
// getOCIRole returns the properties set on the given role.
// This method does NOT check to see if a role upgrade is required. It is
// the responsibility of the caller to check if a role upgrade is required and,
// if so, to upgrade the role
func (b *backend) getOCIRole(ctx context.Context, s logical.Storage, roleName string) (*OCIRoleEntry, error) {
if roleName == "" {
return nil, fmt.Errorf("missing role name")
}
entry, err := s.Get(ctx, "role/"+roleName)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var result OCIRoleEntry
if err := entry.DecodeJSON(&result); err != nil {
return nil, err
}
return &result, nil
}
func (b *backend) pathRoleDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("role").(string)
return nil, req.Storage.Delete(ctx, "role/"+roleName)
}
func (b *backend) pathRoleList(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roles, err := req.Storage.List(ctx, "role/")
if err != nil {
return nil, err
}
return logical.ListResponse(roles), nil
}
func (b *backend) pathRoleRead(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleEntry, err := b.getOCIRole(ctx, req.Storage, data.Get("role").(string))
if err != nil {
return nil, err
}
if roleEntry == nil {
return nil, nil
}
responseData := map[string]interface{}{
"ocid_list": append([]string{}, roleEntry.OcidList...),
}
roleEntry.PopulateTokenData(responseData)
return &logical.Response{
Data: responseData,
}, nil
}
// create a Role
func (b *backend) pathRoleCreateUpdate(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
roleName := data.Get("role").(string)
roleEntry, err := b.getOCIRole(ctx, req.Storage, roleName)
if err != nil {
return nil, err
}
if roleEntry == nil && req.Operation == logical.CreateOperation {
roleEntry = &OCIRoleEntry{}
} else if roleEntry == nil {
return logical.ErrorResponse("The specified role does not exist"), nil
}
if ocidList, ok := data.GetOk("ocid_list"); ok {
roleEntry.OcidList = ocidList.([]string)
if len(roleEntry.OcidList) > MaxOCIDsPerRole {
return logical.ErrorResponse("Number of OCIDs for this role exceeds the limit"), nil
}
}
if err := roleEntry.ParseTokenFields(req, data); err != nil {
return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
}
var resp logical.Response
if err := b.setOCIRole(ctx, req.Storage, roleName, roleEntry); err != nil {
return nil, err
}
return &resp, nil
}
// Struct to hold the information associated with an OCI role
type OCIRoleEntry struct {
tokenutil.TokenParams
OcidList []string `json:"ocid_list"`
}
const pathRoleSyn = `
Create a role and associate policies to it.
`
const pathRoleDesc = `
Create a role and associate policies to it.
`
const pathListRolesHelpSyn = `
Lists all the roles that are registered with Vault.
`
const pathListRolesHelpDesc = `
Roles will be listed by their respective role names.
`

View File

@@ -0,0 +1,32 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
import "github.com/oracle/oci-go-sdk/common"
// Do not edit this file. This is based on standard OCI GO SDK format
// Stores a list of claims of a Principal
type Claim struct {
Key *string `json:"key"`
Value *string `json:"value"`
Issuer *string `json:"issuer"`
}
// Prints the values of pointers in Claim,
// producing a human friendly string for an struct with pointers. Useful when debugging the values of a struct.
func (m Claim) String() string {
return common.PointerString(m)
}
// Stores the details about a Principal
type Principal struct {
TenantId *string `json:"tenantId"`
SubjectId *string `json:"subjectId"`
Claims []Claim `json:"claims"`
}
// Prints the values of pointers in Principal,
// producing a human friendly string for an struct with pointers. Useful when debugging the values of a struct.
func (m Principal) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,34 @@
// Copyright © 2019, Oracle and/or its affiliates.
package ociauth
func sliceToMap(inputSlice []string) map[string]string {
outputMap := make(map[string]string, len(inputSlice))
for _, item := range inputSlice {
outputMap[item] = item
}
return outputMap
}
func mapToSlice(inputMap map[string]string) []string {
outputSlice := make([]string, 0, len(inputMap))
for _, value := range inputMap {
outputSlice = append(outputSlice, value)
}
return outputSlice
}
func addSliceToMap(inputSlice []string, inputMap map[string]string) map[string]string {
for _, item := range inputSlice {
inputMap[item] = item
}
return inputMap
}
func removeSliceFromMap(inputSlice []string, inputMap map[string]string) map[string]string {
for _, item := range inputSlice {
delete(inputMap, item)
}
return inputMap
}

View File

@@ -0,0 +1,7 @@
language: go
go:
- "1.12"
env:
- GO111MODULE=on
script:
- make test

82
vendor/github.com/oracle/oci-go-sdk/LICENSE.txt generated vendored Normal file
View File

@@ -0,0 +1,82 @@
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 or Apache License 2.0. See below for license terms. You may choose either license.
 ____________________________
The Universal Permissive License (UPL), Version 1.0
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this software, associated documentation and/or data (collectively the "Software"), free of charge and under any and all copyright rights in the Software, and any and all patent rights owned or freely licensable by each licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor, or (ii) the Larger Works (as defined below), to deal in both
(a) the Software, and
(b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software (each a "Larger Work" to which the Software is contributed by such licensors),
without restriction, including without limitation the rights to copy, create derivative works of, display, perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other terms.
This license is subject to the following condition:
The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL must 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.
The Apache Software License, Version 2.0
Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); You may not use this product except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. A copy of the license is also reproduced below. 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.
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.

View File

@@ -0,0 +1,260 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package auth
import (
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"sync"
)
// x509CertificateRetriever provides an X509 certificate with the RSA private key
type x509CertificateRetriever interface {
Refresh() error
CertificatePemRaw() []byte
Certificate() *x509.Certificate
PrivateKeyPemRaw() []byte
PrivateKey() *rsa.PrivateKey
}
// urlBasedX509CertificateRetriever retrieves PEM-encoded X509 certificates from the given URLs.
type urlBasedX509CertificateRetriever struct {
certURL string
privateKeyURL string
passphrase string
certificatePemRaw []byte
certificate *x509.Certificate
privateKeyPemRaw []byte
privateKey *rsa.PrivateKey
mux sync.Mutex
dispatcher common.HTTPRequestDispatcher
}
func newURLBasedX509CertificateRetriever(dispatcher common.HTTPRequestDispatcher, certURL, privateKeyURL, passphrase string) x509CertificateRetriever {
return &urlBasedX509CertificateRetriever{
certURL: certURL,
privateKeyURL: privateKeyURL,
passphrase: passphrase,
mux: sync.Mutex{},
dispatcher: dispatcher,
}
}
// Refresh() is failure atomic, i.e., CertificatePemRaw(), Certificate(), PrivateKeyPemRaw(), and PrivateKey() would
// return their previous values if Refresh() fails.
func (r *urlBasedX509CertificateRetriever) Refresh() error {
common.Debugln("Refreshing certificate")
r.mux.Lock()
defer r.mux.Unlock()
var err error
var certificatePemRaw []byte
var certificate *x509.Certificate
if certificatePemRaw, certificate, err = r.renewCertificate(r.certURL); err != nil {
return fmt.Errorf("failed to renew certificate: %s", err.Error())
}
var privateKeyPemRaw []byte
var privateKey *rsa.PrivateKey
if r.privateKeyURL != "" {
if privateKeyPemRaw, privateKey, err = r.renewPrivateKey(r.privateKeyURL, r.passphrase); err != nil {
return fmt.Errorf("failed to renew private key: %s", err.Error())
}
}
r.certificatePemRaw = certificatePemRaw
r.certificate = certificate
r.privateKeyPemRaw = privateKeyPemRaw
r.privateKey = privateKey
return nil
}
func (r *urlBasedX509CertificateRetriever) renewCertificate(url string) (certificatePemRaw []byte, certificate *x509.Certificate, err error) {
var body bytes.Buffer
if body, err = httpGet(r.dispatcher, url); err != nil {
return nil, nil, fmt.Errorf("failed to get certificate from %s: %s", url, err.Error())
}
certificatePemRaw = body.Bytes()
var block *pem.Block
block, _ = pem.Decode(certificatePemRaw)
if block == nil {
return nil, nil, fmt.Errorf("failed to parse the new certificate, not valid pem data")
}
if certificate, err = x509.ParseCertificate(block.Bytes); err != nil {
return nil, nil, fmt.Errorf("failed to parse the new certificate: %s", err.Error())
}
return certificatePemRaw, certificate, nil
}
func (r *urlBasedX509CertificateRetriever) renewPrivateKey(url, passphrase string) (privateKeyPemRaw []byte, privateKey *rsa.PrivateKey, err error) {
var body bytes.Buffer
if body, err = httpGet(r.dispatcher, url); err != nil {
return nil, nil, fmt.Errorf("failed to get private key from %s: %s", url, err.Error())
}
privateKeyPemRaw = body.Bytes()
if privateKey, err = common.PrivateKeyFromBytes(privateKeyPemRaw, &passphrase); err != nil {
return nil, nil, fmt.Errorf("failed to parse the new private key: %s", err.Error())
}
return privateKeyPemRaw, privateKey, nil
}
func (r *urlBasedX509CertificateRetriever) CertificatePemRaw() []byte {
r.mux.Lock()
defer r.mux.Unlock()
if r.certificatePemRaw == nil {
return nil
}
c := make([]byte, len(r.certificatePemRaw))
copy(c, r.certificatePemRaw)
return c
}
func (r *urlBasedX509CertificateRetriever) Certificate() *x509.Certificate {
r.mux.Lock()
defer r.mux.Unlock()
if r.certificate == nil {
return nil
}
c := *r.certificate
return &c
}
func (r *urlBasedX509CertificateRetriever) PrivateKeyPemRaw() []byte {
r.mux.Lock()
defer r.mux.Unlock()
if r.privateKeyPemRaw == nil {
return nil
}
c := make([]byte, len(r.privateKeyPemRaw))
copy(c, r.privateKeyPemRaw)
return c
}
func (r *urlBasedX509CertificateRetriever) PrivateKey() *rsa.PrivateKey {
r.mux.Lock()
defer r.mux.Unlock()
//Nil Private keys are supported as part of a certificate
if r.privateKey == nil {
return nil
}
c := *r.privateKey
return &c
}
//staticCertificateRetriever serves certificates from static data
type staticCertificateRetriever struct {
Passphrase []byte
CertificatePem []byte
PrivateKeyPem []byte
certificate *x509.Certificate
privateKey *rsa.PrivateKey
mux sync.Mutex
}
//Refresh proccess the inputs into appropiate keys and certificates
func (r *staticCertificateRetriever) Refresh() error {
r.mux.Lock()
defer r.mux.Unlock()
certifcate, err := r.readCertificate()
if err != nil {
r.certificate = nil
return err
}
r.certificate = certifcate
key, err := r.readPrivateKey()
if err != nil {
r.privateKey = nil
return err
}
r.privateKey = key
return nil
}
func (r *staticCertificateRetriever) Certificate() *x509.Certificate {
r.mux.Lock()
defer r.mux.Unlock()
return r.certificate
}
func (r *staticCertificateRetriever) PrivateKey() *rsa.PrivateKey {
r.mux.Lock()
defer r.mux.Unlock()
return r.privateKey
}
func (r *staticCertificateRetriever) CertificatePemRaw() []byte {
r.mux.Lock()
defer r.mux.Unlock()
if r.CertificatePem == nil {
return nil
}
c := make([]byte, len(r.CertificatePem))
copy(c, r.CertificatePem)
return c
}
func (r *staticCertificateRetriever) PrivateKeyPemRaw() []byte {
r.mux.Lock()
defer r.mux.Unlock()
if r.PrivateKeyPem == nil {
return nil
}
c := make([]byte, len(r.PrivateKeyPem))
copy(c, r.PrivateKeyPem)
return c
}
func (r *staticCertificateRetriever) readCertificate() (certificate *x509.Certificate, err error) {
block, _ := pem.Decode(r.CertificatePem)
if block == nil {
return nil, fmt.Errorf("failed to parse the new certificate, not valid pem data")
}
if certificate, err = x509.ParseCertificate(block.Bytes); err != nil {
return nil, fmt.Errorf("failed to parse the new certificate: %s", err.Error())
}
return certificate, nil
}
func (r *staticCertificateRetriever) readPrivateKey() (*rsa.PrivateKey, error) {
if r.PrivateKeyPem == nil {
return nil, nil
}
var pass *string
if r.Passphrase == nil {
pass = nil
} else {
ss := string(r.Passphrase)
pass = &ss
}
return common.PrivateKeyFromBytes(r.PrivateKeyPem, pass)
}

View File

@@ -0,0 +1,105 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package auth
import (
"crypto/rsa"
"fmt"
"github.com/oracle/oci-go-sdk/common"
)
type instancePrincipalConfigurationProvider struct {
keyProvider instancePrincipalKeyProvider
region *common.Region
}
//InstancePrincipalConfigurationProvider returns a configuration for instance principals
func InstancePrincipalConfigurationProvider() (common.ConfigurationProvider, error) {
return newInstancePrincipalConfigurationProvider("", nil)
}
//InstancePrincipalConfigurationProviderForRegion returns a configuration for instance principals with a given region
func InstancePrincipalConfigurationProviderForRegion(region common.Region) (common.ConfigurationProvider, error) {
return newInstancePrincipalConfigurationProvider(region, nil)
}
//InstancePrincipalConfigurationProviderWithCustomClient returns a configuration for instance principals using a modifier function to modify the HTTPRequestDispatcher
func InstancePrincipalConfigurationProviderWithCustomClient(modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) (common.ConfigurationProvider, error) {
return newInstancePrincipalConfigurationProvider("", modifier)
}
//InstancePrincipalConfigurationForRegionWithCustomClient returns a configuration for instance principals with a given region using a modifier function to modify the HTTPRequestDispatcher
func InstancePrincipalConfigurationForRegionWithCustomClient(region common.Region, modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) (common.ConfigurationProvider, error) {
return newInstancePrincipalConfigurationProvider(region, modifier)
}
func newInstancePrincipalConfigurationProvider(region common.Region, modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) (common.ConfigurationProvider, error) {
var err error
var keyProvider *instancePrincipalKeyProvider
if keyProvider, err = newInstancePrincipalKeyProvider(modifier); err != nil {
return nil, fmt.Errorf("failed to create a new key provider for instance principal: %s", err.Error())
}
if len(region) > 0 {
return instancePrincipalConfigurationProvider{keyProvider: *keyProvider, region: &region}, nil
}
return instancePrincipalConfigurationProvider{keyProvider: *keyProvider, region: nil}, nil
}
//InstancePrincipalConfigurationWithCerts returns a configuration for instance principals with a given region and hardcoded certificates in lieu of metadata service certs
func InstancePrincipalConfigurationWithCerts(region common.Region, leafCertificate, leafPassphrase, leafPrivateKey []byte, intermediateCertificates [][]byte) (common.ConfigurationProvider, error) {
leafCertificateRetriever := staticCertificateRetriever{Passphrase: leafPassphrase, CertificatePem: leafCertificate, PrivateKeyPem: leafPrivateKey}
//The .Refresh() call actually reads the certificates from the inputs
err := leafCertificateRetriever.Refresh()
if err != nil {
return nil, err
}
certificate := leafCertificateRetriever.Certificate()
tenancyID := extractTenancyIDFromCertificate(certificate)
fedClient, err := newX509FederationClientWithCerts(region, tenancyID, leafCertificate, leafPassphrase, leafPrivateKey, intermediateCertificates, *newDispatcherModifier(nil))
if err != nil {
return nil, err
}
provider := instancePrincipalConfigurationProvider{
keyProvider: instancePrincipalKeyProvider{
Region: region,
FederationClient: fedClient,
TenancyID: tenancyID,
},
region: &region,
}
return provider, nil
}
func (p instancePrincipalConfigurationProvider) PrivateRSAKey() (*rsa.PrivateKey, error) {
return p.keyProvider.PrivateRSAKey()
}
func (p instancePrincipalConfigurationProvider) KeyID() (string, error) {
return p.keyProvider.KeyID()
}
func (p instancePrincipalConfigurationProvider) TenancyOCID() (string, error) {
return p.keyProvider.TenancyOCID()
}
func (p instancePrincipalConfigurationProvider) UserOCID() (string, error) {
return "", nil
}
func (p instancePrincipalConfigurationProvider) KeyFingerprint() (string, error) {
return "", nil
}
func (p instancePrincipalConfigurationProvider) Region() (string, error) {
if p.region == nil {
region := p.keyProvider.RegionForFederationClient()
common.Debugf("Region in instance principal configuration provider is nil. Returning federation clients region: %s", region)
return string(region), nil
}
return string(*p.region), nil
}

View File

@@ -0,0 +1,38 @@
package auth
import "github.com/oracle/oci-go-sdk/common"
//dispatcherModifier gives ability to modify a HTTPRequestDispatcher before use.
type dispatcherModifier struct {
modifiers []func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)
}
//newDispatcherModifier creates a new dispatcherModifier with optional initial modifier (may be nil).
func newDispatcherModifier(modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) *dispatcherModifier {
dispatcherModifier := &dispatcherModifier{
modifiers: make([]func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error), 0),
}
if modifier != nil {
dispatcherModifier.QueueModifier(modifier)
}
return dispatcherModifier
}
//QueueModifier queues up a new modifier
func (c *dispatcherModifier) QueueModifier(modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) {
c.modifiers = append(c.modifiers, modifier)
}
//Modify the provided HTTPRequestDispatcher with this modifier, and return the result, or error if something goes wrong
func (c *dispatcherModifier) Modify(dispatcher common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error) {
if len(c.modifiers) > 0 {
for _, modifier := range c.modifiers {
var err error
if dispatcher, err = modifier(dispatcher); err != nil {
common.Debugf("An error occurred when attempting to modify the dispatcher. Error was: %s", err.Error())
return nil, err
}
}
}
return dispatcher, nil
}

View File

@@ -0,0 +1,335 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
// Package auth provides supporting functions and structs for authentication
package auth
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"net/http"
"os"
"strings"
"sync"
"time"
)
// federationClient is a client to retrieve the security token for an instance principal necessary to sign a request.
// It also provides the private key whose corresponding public key is used to retrieve the security token.
type federationClient interface {
PrivateKey() (*rsa.PrivateKey, error)
SecurityToken() (string, error)
}
// x509FederationClient retrieves a security token from Auth service.
type x509FederationClient struct {
tenancyID string
sessionKeySupplier sessionKeySupplier
leafCertificateRetriever x509CertificateRetriever
intermediateCertificateRetrievers []x509CertificateRetriever
securityToken securityToken
authClient *common.BaseClient
mux sync.Mutex
}
func newX509FederationClient(region common.Region, tenancyID string, leafCertificateRetriever x509CertificateRetriever, intermediateCertificateRetrievers []x509CertificateRetriever, modifier dispatcherModifier) (federationClient, error) {
client := &x509FederationClient{
tenancyID: tenancyID,
leafCertificateRetriever: leafCertificateRetriever,
intermediateCertificateRetrievers: intermediateCertificateRetrievers,
}
client.sessionKeySupplier = newSessionKeySupplier()
authClient := newAuthClient(region, client)
var err error
if authClient.HTTPClient, err = modifier.Modify(authClient.HTTPClient); err != nil {
err = fmt.Errorf("failed to modify client: %s", err.Error())
return nil, err
}
client.authClient = authClient
return client, nil
}
func newX509FederationClientWithCerts(region common.Region, tenancyID string, leafCertificate, leafPassphrase, leafPrivateKey []byte, intermediateCertificates [][]byte, modifier dispatcherModifier) (federationClient, error) {
intermediateRetrievers := make([]x509CertificateRetriever, len(intermediateCertificates))
for i, c := range intermediateCertificates {
intermediateRetrievers[i] = &staticCertificateRetriever{Passphrase: []byte(""), CertificatePem: c, PrivateKeyPem: nil}
}
client := &x509FederationClient{
tenancyID: tenancyID,
leafCertificateRetriever: &staticCertificateRetriever{Passphrase: leafPassphrase, CertificatePem: leafCertificate, PrivateKeyPem: leafPrivateKey},
intermediateCertificateRetrievers: intermediateRetrievers,
}
client.sessionKeySupplier = newSessionKeySupplier()
authClient := newAuthClient(region, client)
var err error
if authClient.HTTPClient, err = modifier.Modify(authClient.HTTPClient); err != nil {
err = fmt.Errorf("failed to modify client: %s", err.Error())
return nil, err
}
client.authClient = authClient
return client, nil
}
var (
genericHeaders = []string{"date", "(request-target)"} // "host" is not needed for the federation endpoint. Don't ask me why.
bodyHeaders = []string{"content-length", "content-type", "x-content-sha256"}
)
func newAuthClient(region common.Region, provider common.KeyProvider) *common.BaseClient {
signer := common.RequestSigner(provider, genericHeaders, bodyHeaders)
client := common.DefaultBaseClientWithSigner(signer)
if regionURL, ok := os.LookupEnv("OCI_SDK_AUTH_CLIENT_REGION_URL"); ok {
client.Host = regionURL
} else {
client.Host = region.Endpoint("auth")
}
client.BasePath = "v1/x509"
return &client
}
// For authClient to sign requests to X509 Federation Endpoint
func (c *x509FederationClient) KeyID() (string, error) {
tenancy := c.tenancyID
fingerprint := fingerprint(c.leafCertificateRetriever.Certificate())
return fmt.Sprintf("%s/fed-x509/%s", tenancy, fingerprint), nil
}
// For authClient to sign requests to X509 Federation Endpoint
func (c *x509FederationClient) PrivateRSAKey() (*rsa.PrivateKey, error) {
key := c.leafCertificateRetriever.PrivateKey()
if key == nil {
return nil, fmt.Errorf("can not read private key from leaf certificate. Likely an error in the metadata service")
}
return key, nil
}
func (c *x509FederationClient) PrivateKey() (*rsa.PrivateKey, error) {
c.mux.Lock()
defer c.mux.Unlock()
if err := c.renewSecurityTokenIfNotValid(); err != nil {
return nil, err
}
return c.sessionKeySupplier.PrivateKey(), nil
}
func (c *x509FederationClient) SecurityToken() (token string, err error) {
c.mux.Lock()
defer c.mux.Unlock()
if err = c.renewSecurityTokenIfNotValid(); err != nil {
return "", err
}
return c.securityToken.String(), nil
}
func (c *x509FederationClient) renewSecurityTokenIfNotValid() (err error) {
if c.securityToken == nil || !c.securityToken.Valid() {
if err = c.renewSecurityToken(); err != nil {
return fmt.Errorf("failed to renew security token: %s", err.Error())
}
}
return nil
}
func (c *x509FederationClient) renewSecurityToken() (err error) {
if err = c.sessionKeySupplier.Refresh(); err != nil {
return fmt.Errorf("failed to refresh session key: %s", err.Error())
}
if err = c.leafCertificateRetriever.Refresh(); err != nil {
return fmt.Errorf("failed to refresh leaf certificate: %s", err.Error())
}
updatedTenancyID := extractTenancyIDFromCertificate(c.leafCertificateRetriever.Certificate())
if c.tenancyID != updatedTenancyID {
err = fmt.Errorf("unexpected update of tenancy OCID in the leaf certificate. Previous tenancy: %s, Updated: %s", c.tenancyID, updatedTenancyID)
return
}
for _, retriever := range c.intermediateCertificateRetrievers {
if err = retriever.Refresh(); err != nil {
return fmt.Errorf("failed to refresh intermediate certificate: %s", err.Error())
}
}
common.Logf("Renewing security token at: %v\n", time.Now().Format("15:04:05.000"))
if c.securityToken, err = c.getSecurityToken(); err != nil {
return fmt.Errorf("failed to get security token: %s", err.Error())
}
common.Logf("Security token renewed at: %v\n", time.Now().Format("15:04:05.000"))
return nil
}
func (c *x509FederationClient) getSecurityToken() (securityToken, error) {
request := c.makeX509FederationRequest()
var err error
var httpRequest http.Request
if httpRequest, err = common.MakeDefaultHTTPRequestWithTaggedStruct(http.MethodPost, "", request); err != nil {
return nil, fmt.Errorf("failed to make http request: %s", err.Error())
}
var httpResponse *http.Response
defer common.CloseBodyIfValid(httpResponse)
if httpResponse, err = c.authClient.Call(context.Background(), &httpRequest); err != nil {
return nil, fmt.Errorf("failed to call: %s", err.Error())
}
response := x509FederationResponse{}
if err = common.UnmarshalResponse(httpResponse, &response); err != nil {
return nil, fmt.Errorf("failed to unmarshal the response: %s", err.Error())
}
return newInstancePrincipalToken(response.Token.Token)
}
type x509FederationRequest struct {
X509FederationDetails `contributesTo:"body"`
}
// X509FederationDetails x509 federation details
type X509FederationDetails struct {
Certificate string `mandatory:"true" json:"certificate,omitempty"`
PublicKey string `mandatory:"true" json:"publicKey,omitempty"`
IntermediateCertificates []string `mandatory:"false" json:"intermediateCertificates,omitempty"`
}
type x509FederationResponse struct {
Token `presentIn:"body"`
}
// Token token
type Token struct {
Token string `mandatory:"true" json:"token,omitempty"`
}
func (c *x509FederationClient) makeX509FederationRequest() *x509FederationRequest {
certificate := c.sanitizeCertificateString(string(c.leafCertificateRetriever.CertificatePemRaw()))
publicKey := c.sanitizeCertificateString(string(c.sessionKeySupplier.PublicKeyPemRaw()))
var intermediateCertificates []string
for _, retriever := range c.intermediateCertificateRetrievers {
intermediateCertificates = append(intermediateCertificates, c.sanitizeCertificateString(string(retriever.CertificatePemRaw())))
}
details := X509FederationDetails{
Certificate: certificate,
PublicKey: publicKey,
IntermediateCertificates: intermediateCertificates,
}
return &x509FederationRequest{details}
}
func (c *x509FederationClient) sanitizeCertificateString(certString string) string {
certString = strings.Replace(certString, "-----BEGIN CERTIFICATE-----", "", -1)
certString = strings.Replace(certString, "-----END CERTIFICATE-----", "", -1)
certString = strings.Replace(certString, "-----BEGIN PUBLIC KEY-----", "", -1)
certString = strings.Replace(certString, "-----END PUBLIC KEY-----", "", -1)
certString = strings.Replace(certString, "\n", "", -1)
return certString
}
// sessionKeySupplier provides an RSA keypair which can be re-generated by calling Refresh().
type sessionKeySupplier interface {
Refresh() error
PrivateKey() *rsa.PrivateKey
PublicKeyPemRaw() []byte
}
// inMemorySessionKeySupplier implements sessionKeySupplier to vend an RSA keypair.
// Refresh() generates a new RSA keypair with a random source, and keeps it in memory.
//
// inMemorySessionKeySupplier is not thread-safe.
type inMemorySessionKeySupplier struct {
keySize int
privateKey *rsa.PrivateKey
publicKeyPemRaw []byte
}
// newSessionKeySupplier creates and returns a sessionKeySupplier instance which generates key pairs of size 2048.
func newSessionKeySupplier() sessionKeySupplier {
return &inMemorySessionKeySupplier{keySize: 2048}
}
// Refresh() is failure atomic, i.e., PrivateKey() and PublicKeyPemRaw() would return their previous values
// if Refresh() fails.
func (s *inMemorySessionKeySupplier) Refresh() (err error) {
common.Debugln("Refreshing session key")
var privateKey *rsa.PrivateKey
privateKey, err = rsa.GenerateKey(rand.Reader, s.keySize)
if err != nil {
return fmt.Errorf("failed to generate a new keypair: %s", err)
}
var publicKeyAsnBytes []byte
if publicKeyAsnBytes, err = x509.MarshalPKIXPublicKey(privateKey.Public()); err != nil {
return fmt.Errorf("failed to marshal the public part of the new keypair: %s", err.Error())
}
publicKeyPemRaw := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyAsnBytes,
})
s.privateKey = privateKey
s.publicKeyPemRaw = publicKeyPemRaw
return nil
}
func (s *inMemorySessionKeySupplier) PrivateKey() *rsa.PrivateKey {
if s.privateKey == nil {
return nil
}
c := *s.privateKey
return &c
}
func (s *inMemorySessionKeySupplier) PublicKeyPemRaw() []byte {
if s.publicKeyPemRaw == nil {
return nil
}
c := make([]byte, len(s.publicKeyPemRaw))
copy(c, s.publicKeyPemRaw)
return c
}
type securityToken interface {
fmt.Stringer
Valid() bool
}
type instancePrincipalToken struct {
tokenString string
jwtToken *jwtToken
}
func newInstancePrincipalToken(tokenString string) (newToken securityToken, err error) {
var jwtToken *jwtToken
if jwtToken, err = parseJwt(tokenString); err != nil {
return nil, fmt.Errorf("failed to parse the token string \"%s\": %s", tokenString, err.Error())
}
return &instancePrincipalToken{tokenString, jwtToken}, nil
}
func (t *instancePrincipalToken) String() string {
return t.tokenString
}
func (t *instancePrincipalToken) Valid() bool {
return !t.jwtToken.expired()
}

View File

@@ -0,0 +1,115 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package auth
import (
"bytes"
"crypto/rsa"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
const (
regionURL = `http://169.254.169.254/opc/v1/instance/region`
leafCertificateURL = `http://169.254.169.254/opc/v1/identity/cert.pem`
leafCertificateKeyURL = `http://169.254.169.254/opc/v1/identity/key.pem`
leafCertificateKeyPassphrase = `` // No passphrase for the private key for Compute instances
intermediateCertificateURL = `http://169.254.169.254/opc/v1/identity/intermediate.pem`
intermediateCertificateKeyURL = ``
intermediateCertificateKeyPassphrase = `` // No passphrase for the private key for Compute instances
)
// instancePrincipalKeyProvider implements KeyProvider to provide a key ID and its corresponding private key
// for an instance principal by getting a security token via x509FederationClient.
//
// The region name of the endpoint for x509FederationClient is obtained from the metadata service on the compute
// instance.
type instancePrincipalKeyProvider struct {
Region common.Region
FederationClient federationClient
TenancyID string
}
// newInstancePrincipalKeyProvider creates and returns an instancePrincipalKeyProvider instance based on
// x509FederationClient.
//
// NOTE: There is a race condition between PrivateRSAKey() and KeyID(). These two pieces are tightly coupled; KeyID
// includes a security token obtained from Auth service by giving a public key which is paired with PrivateRSAKey.
// The x509FederationClient caches the security token in memory until it is expired. Thus, even if a client obtains a
// KeyID that is not expired at the moment, the PrivateRSAKey that the client acquires at a next moment could be
// invalid because the KeyID could be already expired.
func newInstancePrincipalKeyProvider(modifier func(common.HTTPRequestDispatcher) (common.HTTPRequestDispatcher, error)) (provider *instancePrincipalKeyProvider, err error) {
clientModifier := newDispatcherModifier(modifier)
client, err := clientModifier.Modify(&http.Client{})
if err != nil {
err = fmt.Errorf("failed to modify client: %s", err.Error())
return nil, err
}
var region common.Region
if region, err = getRegionForFederationClient(client, regionURL); err != nil {
err = fmt.Errorf("failed to get the region name from %s: %s", regionURL, err.Error())
common.Logf("%v\n", err)
return nil, err
}
leafCertificateRetriever := newURLBasedX509CertificateRetriever(client,
leafCertificateURL, leafCertificateKeyURL, leafCertificateKeyPassphrase)
intermediateCertificateRetrievers := []x509CertificateRetriever{
newURLBasedX509CertificateRetriever(
client, intermediateCertificateURL, intermediateCertificateKeyURL,
intermediateCertificateKeyPassphrase),
}
if err = leafCertificateRetriever.Refresh(); err != nil {
err = fmt.Errorf("failed to refresh the leaf certificate: %s", err.Error())
return nil, err
}
tenancyID := extractTenancyIDFromCertificate(leafCertificateRetriever.Certificate())
federationClient, err := newX509FederationClient(region, tenancyID, leafCertificateRetriever, intermediateCertificateRetrievers, *clientModifier)
if err != nil {
err = fmt.Errorf("failed to create federation client: %s", err.Error())
return nil, err
}
provider = &instancePrincipalKeyProvider{FederationClient: federationClient, TenancyID: tenancyID, Region: region}
return
}
func getRegionForFederationClient(dispatcher common.HTTPRequestDispatcher, url string) (r common.Region, err error) {
var body bytes.Buffer
if body, err = httpGet(dispatcher, url); err != nil {
return
}
return common.StringToRegion(body.String()), nil
}
func (p *instancePrincipalKeyProvider) RegionForFederationClient() common.Region {
return p.Region
}
func (p *instancePrincipalKeyProvider) PrivateRSAKey() (privateKey *rsa.PrivateKey, err error) {
if privateKey, err = p.FederationClient.PrivateKey(); err != nil {
err = fmt.Errorf("failed to get private key: %s", err.Error())
return nil, err
}
return privateKey, nil
}
func (p *instancePrincipalKeyProvider) KeyID() (string, error) {
var securityToken string
var err error
if securityToken, err = p.FederationClient.SecurityToken(); err != nil {
return "", fmt.Errorf("failed to get security token: %s", err.Error())
}
return fmt.Sprintf("ST$%s", securityToken), nil
}
func (p *instancePrincipalKeyProvider) TenancyOCID() (string, error) {
return p.TenancyID, nil
}

69
vendor/github.com/oracle/oci-go-sdk/common/auth/jwt.go generated vendored Normal file
View File

@@ -0,0 +1,69 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package auth
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"strings"
"time"
)
type jwtToken struct {
raw string
header map[string]interface{}
payload map[string]interface{}
}
const bufferTimeBeforeTokenExpiration = 5 * time.Minute
func (t *jwtToken) expired() bool {
exp := int64(t.payload["exp"].(float64))
expTime := time.Unix(exp, 0)
expired := exp <= time.Now().Unix()+int64(bufferTimeBeforeTokenExpiration.Seconds())
if expired {
common.Debugf("Token expires at: %v, currently expired due to bufferTime: %v", expTime.Format("15:04:05.000"), expired)
}
return expired
}
func parseJwt(tokenString string) (*jwtToken, error) {
parts := strings.Split(tokenString, ".")
if len(parts) != 3 {
return nil, fmt.Errorf("the given token string contains an invalid number of parts")
}
token := &jwtToken{raw: tokenString}
var err error
// Parse Header part
var headerBytes []byte
if headerBytes, err = decodePart(parts[0]); err != nil {
return nil, fmt.Errorf("failed to decode the header bytes: %s", err.Error())
}
if err = json.Unmarshal(headerBytes, &token.header); err != nil {
return nil, err
}
// Parse Payload part
var payloadBytes []byte
if payloadBytes, err = decodePart(parts[1]); err != nil {
return nil, fmt.Errorf("failed to decode the payload bytes: %s", err.Error())
}
decoder := json.NewDecoder(bytes.NewBuffer(payloadBytes))
if err = decoder.Decode(&token.payload); err != nil {
return nil, fmt.Errorf("failed to decode the payload json: %s", err.Error())
}
return token, nil
}
func decodePart(partString string) ([]byte, error) {
if l := len(partString) % 4; 0 < l {
partString += strings.Repeat("=", 4-l)
}
return base64.URLEncoding.DecodeString(partString)
}

View File

@@ -0,0 +1,66 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package auth
import (
"bytes"
"crypto/sha1"
"crypto/x509"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"net/http"
"net/http/httputil"
"strings"
)
// httpGet makes a simple HTTP GET request to the given URL, expecting only "200 OK" status code.
// This is basically for the Instance Metadata Service.
func httpGet(dispatcher common.HTTPRequestDispatcher, url string) (body bytes.Buffer, err error) {
var response *http.Response
request, err := http.NewRequest(http.MethodGet, url, nil)
if response, err = dispatcher.Do(request); err != nil {
return
}
common.IfDebug(func() {
if dump, e := httputil.DumpResponse(response, true); e == nil {
common.Logf("Dump Response %v", string(dump))
} else {
common.Debugln(e)
}
})
defer response.Body.Close()
if _, err = body.ReadFrom(response.Body); err != nil {
return
}
if response.StatusCode != http.StatusOK {
err = fmt.Errorf("HTTP Get failed: URL: %s, Status: %s, Message: %s",
url, response.Status, body.String())
return
}
return
}
func extractTenancyIDFromCertificate(cert *x509.Certificate) string {
for _, nameAttr := range cert.Subject.Names {
value := nameAttr.Value.(string)
if strings.HasPrefix(value, "opc-tenant:") {
return value[len("opc-tenant:"):]
}
}
return ""
}
func fingerprint(certificate *x509.Certificate) string {
fingerprint := sha1.Sum(certificate.Raw)
return colonSeparatedString(fingerprint)
}
func colonSeparatedString(fingerprint [sha1.Size]byte) string {
spaceSeparated := fmt.Sprintf("% x", fingerprint)
return strings.Replace(spaceSeparated, " ", ":", -1)
}

339
vendor/github.com/oracle/oci-go-sdk/common/client.go generated vendored Normal file
View File

@@ -0,0 +1,339 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
// Package common provides supporting functions and structs used by service packages
package common
import (
"context"
"fmt"
"math/rand"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/user"
"path"
"runtime"
"strings"
"sync/atomic"
"time"
)
const (
// DefaultHostURLTemplate The default url template for service hosts
DefaultHostURLTemplate = "%s.%s.oraclecloud.com"
// requestHeaderAccept The key for passing a header to indicate Accept
requestHeaderAccept = "Accept"
// requestHeaderAuthorization The key for passing a header to indicate Authorization
requestHeaderAuthorization = "Authorization"
// requestHeaderContentLength The key for passing a header to indicate Content Length
requestHeaderContentLength = "Content-Length"
// requestHeaderContentType The key for passing a header to indicate Content Type
requestHeaderContentType = "Content-Type"
// requestHeaderDate The key for passing a header to indicate Date
requestHeaderDate = "Date"
// requestHeaderIfMatch The key for passing a header to indicate If Match
requestHeaderIfMatch = "if-match"
// requestHeaderOpcClientInfo The key for passing a header to indicate OPC Client Info
requestHeaderOpcClientInfo = "opc-client-info"
// requestHeaderOpcRetryToken The key for passing a header to indicate OPC Retry Token
requestHeaderOpcRetryToken = "opc-retry-token"
// requestHeaderOpcRequestID The key for unique Oracle-assigned identifier for the request.
requestHeaderOpcRequestID = "opc-request-id"
// requestHeaderOpcClientRequestID The key for unique Oracle-assigned identifier for the request.
requestHeaderOpcClientRequestID = "opc-client-request-id"
// requestHeaderUserAgent The key for passing a header to indicate User Agent
requestHeaderUserAgent = "User-Agent"
// requestHeaderXContentSHA256 The key for passing a header to indicate SHA256 hash
requestHeaderXContentSHA256 = "X-Content-SHA256"
// private constants
defaultScheme = "https"
defaultSDKMarker = "Oracle-GoSDK"
defaultUserAgentTemplate = "%s/%s (%s/%s; go/%s)" //SDK/SDKVersion (OS/OSVersion; Lang/LangVersion)
defaultTimeout = 60 * time.Second
defaultConfigFileName = "config"
defaultConfigDirName = ".oci"
secondaryConfigDirName = ".oraclebmc"
maxBodyLenForDebug = 1024 * 1000
)
// RequestInterceptor function used to customize the request before calling the underlying service
type RequestInterceptor func(*http.Request) error
// HTTPRequestDispatcher wraps the execution of a http request, it is generally implemented by
// http.Client.Do, but can be customized for testing
type HTTPRequestDispatcher interface {
Do(req *http.Request) (*http.Response, error)
}
// BaseClient struct implements all basic operations to call oci web services.
type BaseClient struct {
//HTTPClient performs the http network operations
HTTPClient HTTPRequestDispatcher
//Signer performs auth operation
Signer HTTPRequestSigner
//A request interceptor can be used to customize the request before signing and dispatching
Interceptor RequestInterceptor
//The host of the service
Host string
//The user agent
UserAgent string
//Base path for all operations of this client
BasePath string
}
func defaultUserAgent() string {
userAgent := fmt.Sprintf(defaultUserAgentTemplate, defaultSDKMarker, Version(), runtime.GOOS, runtime.GOARCH, runtime.Version())
return userAgent
}
var clientCounter int64
func getNextSeed() int64 {
newCounterValue := atomic.AddInt64(&clientCounter, 1)
return newCounterValue + time.Now().UnixNano()
}
func newBaseClient(signer HTTPRequestSigner, dispatcher HTTPRequestDispatcher) BaseClient {
rand.Seed(getNextSeed())
return BaseClient{
UserAgent: defaultUserAgent(),
Interceptor: nil,
Signer: signer,
HTTPClient: dispatcher,
}
}
func defaultHTTPDispatcher() http.Client {
httpClient := http.Client{
Timeout: defaultTimeout,
}
return httpClient
}
func defaultBaseClient(provider KeyProvider) BaseClient {
dispatcher := defaultHTTPDispatcher()
signer := DefaultRequestSigner(provider)
return newBaseClient(signer, &dispatcher)
}
//DefaultBaseClientWithSigner creates a default base client with a given signer
func DefaultBaseClientWithSigner(signer HTTPRequestSigner) BaseClient {
dispatcher := defaultHTTPDispatcher()
return newBaseClient(signer, &dispatcher)
}
// NewClientWithConfig Create a new client with a configuration provider, the configuration provider
// will be used for the default signer as well as reading the region
// This function does not check for valid regions to implement forward compatibility
func NewClientWithConfig(configProvider ConfigurationProvider) (client BaseClient, err error) {
var ok bool
if ok, err = IsConfigurationProviderValid(configProvider); !ok {
err = fmt.Errorf("can not create client, bad configuration: %s", err.Error())
return
}
client = defaultBaseClient(configProvider)
return
}
func getHomeFolder() string {
current, e := user.Current()
if e != nil {
//Give up and try to return something sensible
home := os.Getenv("HOME")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return current.HomeDir
}
// DefaultConfigProvider returns the default config provider. The default config provider
// will look for configurations in 3 places: file in $HOME/.oci/config, HOME/.obmcs/config and
// variables names starting with the string TF_VAR. If the same configuration is found in multiple
// places the provider will prefer the first one.
func DefaultConfigProvider() ConfigurationProvider {
homeFolder := getHomeFolder()
defaultConfigFile := path.Join(homeFolder, defaultConfigDirName, defaultConfigFileName)
secondaryConfigFile := path.Join(homeFolder, secondaryConfigDirName, defaultConfigFileName)
defaultFileProvider, _ := ConfigurationProviderFromFile(defaultConfigFile, "")
secondaryFileProvider, _ := ConfigurationProviderFromFile(secondaryConfigFile, "")
environmentProvider := environmentConfigurationProvider{EnvironmentVariablePrefix: "TF_VAR"}
provider, _ := ComposingConfigurationProvider([]ConfigurationProvider{defaultFileProvider, secondaryFileProvider, environmentProvider})
Debugf("Configuration provided by: %s", provider)
return provider
}
func (client *BaseClient) prepareRequest(request *http.Request) (err error) {
if client.UserAgent == "" {
return fmt.Errorf("user agent can not be blank")
}
if request.Header == nil {
request.Header = http.Header{}
}
request.Header.Set(requestHeaderUserAgent, client.UserAgent)
request.Header.Set(requestHeaderDate, time.Now().UTC().Format(http.TimeFormat))
if !strings.Contains(client.Host, "http") &&
!strings.Contains(client.Host, "https") {
client.Host = fmt.Sprintf("%s://%s", defaultScheme, client.Host)
}
clientURL, err := url.Parse(client.Host)
if err != nil {
return fmt.Errorf("host is invalid. %s", err.Error())
}
request.URL.Host = clientURL.Host
request.URL.Scheme = clientURL.Scheme
currentPath := request.URL.Path
if !strings.Contains(currentPath, fmt.Sprintf("/%s", client.BasePath)) {
request.URL.Path = path.Clean(fmt.Sprintf("/%s/%s", client.BasePath, currentPath))
}
return
}
func (client BaseClient) intercept(request *http.Request) (err error) {
if client.Interceptor != nil {
err = client.Interceptor(request)
}
return
}
func checkForSuccessfulResponse(res *http.Response) error {
familyStatusCode := res.StatusCode / 100
if familyStatusCode == 4 || familyStatusCode == 5 {
return newServiceFailureFromResponse(res)
}
return nil
}
// OCIRequest is any request made to an OCI service.
type OCIRequest interface {
// HTTPRequest assembles an HTTP request.
HTTPRequest(method, path string) (http.Request, error)
}
// RequestMetadata is metadata about an OCIRequest. This structure represents the behavior exhibited by the SDK when
// issuing (or reissuing) a request.
type RequestMetadata struct {
// RetryPolicy is the policy for reissuing the request. If no retry policy is set on the request,
// then the request will be issued exactly once.
RetryPolicy *RetryPolicy
}
// OCIResponse is the response from issuing a request to an OCI service.
type OCIResponse interface {
// HTTPResponse returns the raw HTTP response.
HTTPResponse() *http.Response
}
// OCIOperation is the generalization of a request-response cycle undergone by an OCI service.
type OCIOperation func(context.Context, OCIRequest) (OCIResponse, error)
//ClientCallDetails a set of settings used by the a single Call operation of the http Client
type ClientCallDetails struct {
Signer HTTPRequestSigner
}
// Call executes the http request with the given context
func (client BaseClient) Call(ctx context.Context, request *http.Request) (response *http.Response, err error) {
return client.CallWithDetails(ctx, request, ClientCallDetails{Signer: client.Signer})
}
// CallWithDetails executes the http request, the given context using details specified in the paremeters, this function
// provides a way to override some settings present in the client
func (client BaseClient) CallWithDetails(ctx context.Context, request *http.Request, details ClientCallDetails) (response *http.Response, err error) {
Debugln("Atempting to call downstream service")
request = request.WithContext(ctx)
err = client.prepareRequest(request)
if err != nil {
return
}
//Intercept
err = client.intercept(request)
if err != nil {
return
}
//Sign the request
err = details.Signer.Sign(request)
if err != nil {
return
}
IfDebug(func() {
dumpBody := true
if request.ContentLength > maxBodyLenForDebug {
Debugf("not dumping body too big\n")
dumpBody = false
}
dumpBody = dumpBody && defaultLogger.LogLevel() == verboseLogging
if dump, e := httputil.DumpRequestOut(request, dumpBody); e == nil {
Debugf("Dump Request %s", string(dump))
} else {
Debugf("%v\n", e)
}
})
//Execute the http request
response, err = client.HTTPClient.Do(request)
IfDebug(func() {
if err != nil {
Debugf("%v\n", err)
return
}
dumpBody := true
if response.ContentLength > maxBodyLenForDebug {
Debugf("not dumping body too big\n")
dumpBody = false
}
dumpBody = dumpBody && defaultLogger.LogLevel() == verboseLogging
if dump, e := httputil.DumpResponse(response, dumpBody); e == nil {
Debugf("Dump Response %s", string(dump))
} else {
Debugf("%v\n", e)
}
})
if err != nil {
return
}
err = checkForSuccessfulResponse(response)
return
}
//CloseBodyIfValid closes the body of an http response if the response and the body are valid
func CloseBodyIfValid(httpResponse *http.Response) {
if httpResponse != nil && httpResponse.Body != nil {
httpResponse.Body.Close()
}
}

156
vendor/github.com/oracle/oci-go-sdk/common/common.go generated vendored Normal file
View File

@@ -0,0 +1,156 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package common
import (
"fmt"
"regexp"
"strings"
)
//Region type for regions
type Region string
const (
//RegionSEA region SEA
RegionSEA Region = "sea"
//RegionCAToronto1 region for toronto
RegionCAToronto1 Region = "ca-toronto-1"
//RegionPHX region PHX
RegionPHX Region = "us-phoenix-1"
//RegionIAD region IAD
RegionIAD Region = "us-ashburn-1"
//RegionFRA region FRA
RegionFRA Region = "eu-frankfurt-1"
//RegionLHR region LHR
RegionLHR Region = "uk-london-1"
//RegionAPTokyo1 region for tokyo
RegionAPTokyo1 Region = "ap-tokyo-1"
//RegionAPSeoul1 region for seoul
RegionAPSeoul1 Region = "ap-seoul-1"
//RegionAPMumbai1 region for mumbai
RegionAPMumbai1 Region = "ap-mumbai-1"
//RegionEUZurich1 region for Zurich
RegionEUZurich1 Region = "eu-zurich-1"
//RegionUSLangley1 region for langley
RegionUSLangley1 Region = "us-langley-1"
//RegionUSLuke1 region for luke
RegionUSLuke1 Region = "us-luke-1"
//RegionUSGovAshburn1 region for langley
RegionUSGovAshburn1 Region = "us-gov-ashburn-1"
//RegionUSGovChicago1 region for luke
RegionUSGovChicago1 Region = "us-gov-chicago-1"
//RegionUSGovPhoenix1 region for luke
RegionUSGovPhoenix1 Region = "us-gov-phoenix-1"
)
var realm = map[string]string{
"oc1": "oraclecloud.com",
"oc2": "oraclegovcloud.com",
"oc3": "oraclegovcloud.com",
}
var regionRealm = map[Region]string{
RegionPHX: "oc1",
RegionIAD: "oc1",
RegionFRA: "oc1",
RegionLHR: "oc1",
RegionCAToronto1: "oc1",
RegionAPTokyo1: "oc1",
RegionAPSeoul1: "oc1",
RegionAPMumbai1: "oc1",
RegionEUZurich1: "oc1",
RegionUSLangley1: "oc2",
RegionUSLuke1: "oc2",
RegionUSGovAshburn1: "oc3",
RegionUSGovChicago1: "oc3",
RegionUSGovPhoenix1: "oc3",
}
// Endpoint returns a endpoint for a service
func (region Region) Endpoint(service string) string {
return fmt.Sprintf("%s.%s.%s", service, region, region.secondLevelDomain())
}
// EndpointForTemplate returns a endpoint for a service based on template
func (region Region) EndpointForTemplate(service string, serviceEndpointTemplate string) string {
if serviceEndpointTemplate == "" {
return region.Endpoint(service)
}
// replace service prefix
endpoint := strings.Replace(serviceEndpointTemplate, "{serviceEndpointPrefix}", service, 1)
// replace region
endpoint = strings.Replace(endpoint, "{region}", string(region), 1)
// replace second level domain
endpoint = strings.Replace(endpoint, "{secondLevelDomain}", region.secondLevelDomain(), 1)
return endpoint
}
func (region Region) secondLevelDomain() string {
if realmID, ok := regionRealm[region]; ok {
if secondLevelDomain, ok := realm[realmID]; ok {
return secondLevelDomain
}
}
Debugf("cannot find realm for region : %s, return default realm value.", region)
return realm["oc1"]
}
//StringToRegion convert a string to Region type
func StringToRegion(stringRegion string) (r Region) {
switch strings.ToLower(stringRegion) {
case "sea":
r = RegionSEA
case "ca-toronto-1":
r = RegionCAToronto1
case "phx", "us-phoenix-1":
r = RegionPHX
case "iad", "us-ashburn-1":
r = RegionIAD
case "fra", "eu-frankfurt-1":
r = RegionFRA
case "lhr", "uk-london-1":
r = RegionLHR
case "ap-tokyo-1":
r = RegionAPTokyo1
case "ap-seoul-1":
r = RegionAPSeoul1
case "ap-mumbai-1":
r = RegionAPMumbai1
case "eu-zurich-1":
r = RegionEUZurich1
case "us-langley-1":
r = RegionUSLangley1
case "us-luke-1":
r = RegionUSLuke1
case "us-gov-ashburn-1":
r = RegionUSGovAshburn1
case "us-gov-chicago-1":
r = RegionUSGovChicago1
case "us-gov-phoenix-1":
r = RegionUSGovPhoenix1
default:
r = Region(stringRegion)
Debugf("region named: %s, is not recognized", stringRegion)
}
return
}
// canStringBeRegion test if the string can be a region, if it can, returns the string as is, otherwise it
// returns an error
var blankRegex = regexp.MustCompile("\\s")
func canStringBeRegion(stringRegion string) (region string, err error) {
if blankRegex.MatchString(stringRegion) || stringRegion == "" {
return "", fmt.Errorf("region can not be empty or have spaces")
}
return stringRegion, nil
}

View File

@@ -0,0 +1,535 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package common
import (
"crypto/rsa"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
)
// ConfigurationProvider wraps information about the account owner
type ConfigurationProvider interface {
KeyProvider
TenancyOCID() (string, error)
UserOCID() (string, error)
KeyFingerprint() (string, error)
Region() (string, error)
}
// IsConfigurationProviderValid Tests all parts of the configuration provider do not return an error
func IsConfigurationProviderValid(conf ConfigurationProvider) (ok bool, err error) {
baseFn := []func() (string, error){conf.TenancyOCID, conf.UserOCID, conf.KeyFingerprint, conf.Region, conf.KeyID}
for _, fn := range baseFn {
_, err = fn()
ok = err == nil
if err != nil {
return
}
}
_, err = conf.PrivateRSAKey()
ok = err == nil
if err != nil {
return
}
return true, nil
}
// rawConfigurationProvider allows a user to simply construct a configuration provider from raw values.
type rawConfigurationProvider struct {
tenancy string
user string
region string
fingerprint string
privateKey string
privateKeyPassphrase *string
}
// NewRawConfigurationProvider will create a ConfigurationProvider with the arguments of the function
func NewRawConfigurationProvider(tenancy, user, region, fingerprint, privateKey string, privateKeyPassphrase *string) ConfigurationProvider {
return rawConfigurationProvider{tenancy, user, region, fingerprint, privateKey, privateKeyPassphrase}
}
func (p rawConfigurationProvider) PrivateRSAKey() (key *rsa.PrivateKey, err error) {
return PrivateKeyFromBytes([]byte(p.privateKey), p.privateKeyPassphrase)
}
func (p rawConfigurationProvider) KeyID() (keyID string, err error) {
tenancy, err := p.TenancyOCID()
if err != nil {
return
}
user, err := p.UserOCID()
if err != nil {
return
}
fingerprint, err := p.KeyFingerprint()
if err != nil {
return
}
return fmt.Sprintf("%s/%s/%s", tenancy, user, fingerprint), nil
}
func (p rawConfigurationProvider) TenancyOCID() (string, error) {
if p.tenancy == "" {
return "", fmt.Errorf("tenancy OCID can not be empty")
}
return p.tenancy, nil
}
func (p rawConfigurationProvider) UserOCID() (string, error) {
if p.user == "" {
return "", fmt.Errorf("user OCID can not be empty")
}
return p.user, nil
}
func (p rawConfigurationProvider) KeyFingerprint() (string, error) {
if p.fingerprint == "" {
return "", fmt.Errorf("fingerprint can not be empty")
}
return p.fingerprint, nil
}
func (p rawConfigurationProvider) Region() (string, error) {
return canStringBeRegion(p.region)
}
// environmentConfigurationProvider reads configuration from environment variables
type environmentConfigurationProvider struct {
PrivateKeyPassword string
EnvironmentVariablePrefix string
}
// ConfigurationProviderEnvironmentVariables creates a ConfigurationProvider from a uniform set of environment variables starting with a prefix
// The env variables should look like: [prefix]_private_key_path, [prefix]_tenancy_ocid, [prefix]_user_ocid, [prefix]_fingerprint
// [prefix]_region
func ConfigurationProviderEnvironmentVariables(environmentVariablePrefix, privateKeyPassword string) ConfigurationProvider {
return environmentConfigurationProvider{EnvironmentVariablePrefix: environmentVariablePrefix,
PrivateKeyPassword: privateKeyPassword}
}
func (p environmentConfigurationProvider) String() string {
return fmt.Sprintf("Configuration provided by environment variables prefixed with: %s", p.EnvironmentVariablePrefix)
}
func (p environmentConfigurationProvider) PrivateRSAKey() (key *rsa.PrivateKey, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "private_key_path")
var ok bool
var value string
if value, ok = os.LookupEnv(environmentVariable); !ok {
return nil, fmt.Errorf("can not read PrivateKey from env variable: %s", environmentVariable)
}
expandedPath := expandPath(value)
pemFileContent, err := ioutil.ReadFile(expandedPath)
if err != nil {
Debugln("Can not read PrivateKey location from environment variable: " + environmentVariable)
return
}
key, err = PrivateKeyFromBytes(pemFileContent, &p.PrivateKeyPassword)
return
}
func (p environmentConfigurationProvider) KeyID() (keyID string, err error) {
ocid, err := p.TenancyOCID()
if err != nil {
return
}
userocid, err := p.UserOCID()
if err != nil {
return
}
fingerprint, err := p.KeyFingerprint()
if err != nil {
return
}
return fmt.Sprintf("%s/%s/%s", ocid, userocid, fingerprint), nil
}
func (p environmentConfigurationProvider) TenancyOCID() (value string, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "tenancy_ocid")
var ok bool
if value, ok = os.LookupEnv(environmentVariable); !ok {
err = fmt.Errorf("can not read Tenancy from environment variable %s", environmentVariable)
}
return
}
func (p environmentConfigurationProvider) UserOCID() (value string, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "user_ocid")
var ok bool
if value, ok = os.LookupEnv(environmentVariable); !ok {
err = fmt.Errorf("can not read user id from environment variable %s", environmentVariable)
}
return
}
func (p environmentConfigurationProvider) KeyFingerprint() (value string, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "fingerprint")
var ok bool
if value, ok = os.LookupEnv(environmentVariable); !ok {
err = fmt.Errorf("can not read fingerprint from environment variable %s", environmentVariable)
}
return
}
func (p environmentConfigurationProvider) Region() (value string, err error) {
environmentVariable := fmt.Sprintf("%s_%s", p.EnvironmentVariablePrefix, "region")
var ok bool
if value, ok = os.LookupEnv(environmentVariable); !ok {
err = fmt.Errorf("can not read region from environment variable %s", environmentVariable)
return value, err
}
return canStringBeRegion(value)
}
// fileConfigurationProvider. reads configuration information from a file
type fileConfigurationProvider struct {
//The path to the configuration file
ConfigPath string
//The password for the private key
PrivateKeyPassword string
//The profile for the configuration
Profile string
//ConfigFileInfo
FileInfo *configFileInfo
}
// ConfigurationProviderFromFile creates a configuration provider from a configuration file
// by reading the "DEFAULT" profile
func ConfigurationProviderFromFile(configFilePath, privateKeyPassword string) (ConfigurationProvider, error) {
if configFilePath == "" {
return nil, fmt.Errorf("config file path can not be empty")
}
return fileConfigurationProvider{
ConfigPath: configFilePath,
PrivateKeyPassword: privateKeyPassword,
Profile: "DEFAULT"}, nil
}
// ConfigurationProviderFromFileWithProfile creates a configuration provider from a configuration file
// and the given profile
func ConfigurationProviderFromFileWithProfile(configFilePath, profile, privateKeyPassword string) (ConfigurationProvider, error) {
if configFilePath == "" {
return nil, fmt.Errorf("config file path can not be empty")
}
return fileConfigurationProvider{
ConfigPath: configFilePath,
PrivateKeyPassword: privateKeyPassword,
Profile: profile}, nil
}
type configFileInfo struct {
UserOcid, Fingerprint, KeyFilePath, TenancyOcid, Region, Passphrase string
PresentConfiguration byte
}
const (
hasTenancy = 1 << iota
hasUser
hasFingerprint
hasRegion
hasKeyFile
hasPassphrase
none
)
var profileRegex = regexp.MustCompile(`^\[(.*)\]`)
func parseConfigFile(data []byte, profile string) (info *configFileInfo, err error) {
if len(data) == 0 {
return nil, fmt.Errorf("configuration file content is empty")
}
content := string(data)
splitContent := strings.Split(content, "\n")
//Look for profile
for i, line := range splitContent {
if match := profileRegex.FindStringSubmatch(line); match != nil && len(match) > 1 && match[1] == profile {
start := i + 1
return parseConfigAtLine(start, splitContent)
}
}
return nil, fmt.Errorf("configuration file did not contain profile: %s", profile)
}
func parseConfigAtLine(start int, content []string) (info *configFileInfo, err error) {
var configurationPresent byte
info = &configFileInfo{}
for i := start; i < len(content); i++ {
line := content[i]
if profileRegex.MatchString(line) {
break
}
if !strings.Contains(line, "=") {
continue
}
splits := strings.Split(line, "=")
switch key, value := strings.TrimSpace(splits[0]), strings.TrimSpace(splits[1]); strings.ToLower(key) {
case "passphrase", "pass_phrase":
configurationPresent = configurationPresent | hasPassphrase
info.Passphrase = value
case "user":
configurationPresent = configurationPresent | hasUser
info.UserOcid = value
case "fingerprint":
configurationPresent = configurationPresent | hasFingerprint
info.Fingerprint = value
case "key_file":
configurationPresent = configurationPresent | hasKeyFile
info.KeyFilePath = value
case "tenancy":
configurationPresent = configurationPresent | hasTenancy
info.TenancyOcid = value
case "region":
configurationPresent = configurationPresent | hasRegion
info.Region = value
}
}
info.PresentConfiguration = configurationPresent
return
}
// cleans and expands the path if it contains a tilde , returns the expanded path or the input path as is if not expansion
// was performed
func expandPath(filepath string) (expandedPath string) {
cleanedPath := path.Clean(filepath)
expandedPath = cleanedPath
if strings.HasPrefix(cleanedPath, "~") {
rest := cleanedPath[2:]
expandedPath = path.Join(getHomeFolder(), rest)
}
return
}
func openConfigFile(configFilePath string) (data []byte, err error) {
expandedPath := expandPath(configFilePath)
data, err = ioutil.ReadFile(expandedPath)
if err != nil {
err = fmt.Errorf("can not read config file: %s due to: %s", configFilePath, err.Error())
}
return
}
func (p fileConfigurationProvider) String() string {
return fmt.Sprintf("Configuration provided by file: %s", p.ConfigPath)
}
func (p fileConfigurationProvider) readAndParseConfigFile() (info *configFileInfo, err error) {
if p.FileInfo != nil {
return p.FileInfo, nil
}
if p.ConfigPath == "" {
return nil, fmt.Errorf("configuration path can not be empty")
}
data, err := openConfigFile(p.ConfigPath)
if err != nil {
err = fmt.Errorf("error while parsing config file: %s. Due to: %s", p.ConfigPath, err.Error())
return
}
p.FileInfo, err = parseConfigFile(data, p.Profile)
return p.FileInfo, err
}
func presentOrError(value string, expectedConf, presentConf byte, confMissing string) (string, error) {
if presentConf&expectedConf == expectedConf {
return value, nil
}
return "", errors.New(confMissing + " configuration is missing from file")
}
func (p fileConfigurationProvider) TenancyOCID() (value string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
value, err = presentOrError(info.TenancyOcid, hasTenancy, info.PresentConfiguration, "tenancy")
return
}
func (p fileConfigurationProvider) UserOCID() (value string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
value, err = presentOrError(info.UserOcid, hasUser, info.PresentConfiguration, "user")
return
}
func (p fileConfigurationProvider) KeyFingerprint() (value string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
value, err = presentOrError(info.Fingerprint, hasFingerprint, info.PresentConfiguration, "fingerprint")
return
}
func (p fileConfigurationProvider) KeyID() (keyID string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
return fmt.Sprintf("%s/%s/%s", info.TenancyOcid, info.UserOcid, info.Fingerprint), nil
}
func (p fileConfigurationProvider) PrivateRSAKey() (key *rsa.PrivateKey, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read tenancy configuration due to: %s", err.Error())
return
}
filePath, err := presentOrError(info.KeyFilePath, hasKeyFile, info.PresentConfiguration, "key file path")
if err != nil {
return
}
expandedPath := expandPath(filePath)
pemFileContent, err := ioutil.ReadFile(expandedPath)
if err != nil {
err = fmt.Errorf("can not read PrivateKey from configuration file due to: %s", err.Error())
return
}
password := p.PrivateKeyPassword
if password == "" && ((info.PresentConfiguration & hasPassphrase) == hasPassphrase) {
password = info.Passphrase
}
key, err = PrivateKeyFromBytes(pemFileContent, &password)
return
}
func (p fileConfigurationProvider) Region() (value string, err error) {
info, err := p.readAndParseConfigFile()
if err != nil {
err = fmt.Errorf("can not read region configuration due to: %s", err.Error())
return
}
value, err = presentOrError(info.Region, hasRegion, info.PresentConfiguration, "region")
if err != nil {
return
}
return canStringBeRegion(value)
}
// A configuration provider that look for information in multiple configuration providers
type composingConfigurationProvider struct {
Providers []ConfigurationProvider
}
// ComposingConfigurationProvider creates a composing configuration provider with the given slice of configuration providers
// A composing provider will return the configuration of the first provider that has the required property
// if no provider has the property it will return an error.
func ComposingConfigurationProvider(providers []ConfigurationProvider) (ConfigurationProvider, error) {
if len(providers) == 0 {
return nil, fmt.Errorf("providers can not be an empty slice")
}
for i, p := range providers {
if p == nil {
return nil, fmt.Errorf("provider in position: %d is nil. ComposingConfiurationProvider does not support nil values", i)
}
}
return composingConfigurationProvider{Providers: providers}, nil
}
func (c composingConfigurationProvider) TenancyOCID() (string, error) {
for _, p := range c.Providers {
val, err := p.TenancyOCID()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for tenancy")
}
func (c composingConfigurationProvider) UserOCID() (string, error) {
for _, p := range c.Providers {
val, err := p.UserOCID()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for user")
}
func (c composingConfigurationProvider) KeyFingerprint() (string, error) {
for _, p := range c.Providers {
val, err := p.KeyFingerprint()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for keyFingerprint")
}
func (c composingConfigurationProvider) Region() (string, error) {
for _, p := range c.Providers {
val, err := p.Region()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for region")
}
func (c composingConfigurationProvider) KeyID() (string, error) {
for _, p := range c.Providers {
val, err := p.KeyID()
if err == nil {
return val, nil
}
}
return "", fmt.Errorf("did not find a proper configuration for key id")
}
func (c composingConfigurationProvider) PrivateRSAKey() (*rsa.PrivateKey, error) {
for _, p := range c.Providers {
val, err := p.PrivateRSAKey()
if err == nil {
return val, nil
}
}
return nil, fmt.Errorf("did not find a proper configuration for private key")
}

98
vendor/github.com/oracle/oci-go-sdk/common/errors.go generated vendored Normal file
View File

@@ -0,0 +1,98 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package common
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// ServiceError models all potential errors generated the service call
type ServiceError interface {
// The http status code of the error
GetHTTPStatusCode() int
// The human-readable error string as sent by the service
GetMessage() string
// A short error code that defines the error, meant for programmatic parsing.
// See https://docs.cloud.oracle.com/Content/API/References/apierrors.htm
GetCode() string
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
GetOpcRequestID() string
}
type servicefailure struct {
StatusCode int
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
OpcRequestID string `json:"opc-request-id"`
}
func newServiceFailureFromResponse(response *http.Response) error {
var err error
se := servicefailure{
StatusCode: response.StatusCode,
Code: "BadErrorResponse",
OpcRequestID: response.Header.Get("opc-request-id")}
//If there is an error consume the body, entirely
body, err := ioutil.ReadAll(response.Body)
if err != nil {
se.Message = fmt.Sprintf("The body of the response was not readable, due to :%s", err.Error())
return se
}
err = json.Unmarshal(body, &se)
if err != nil {
Debugf("Error response could not be parsed due to: %s", err.Error())
se.Message = fmt.Sprintf("Failed to parse json from response body due to: %s. With response body %s.", err.Error(), string(body[:]))
return se
}
return se
}
func (se servicefailure) Error() string {
return fmt.Sprintf("Service error:%s. %s. http status code: %d. Opc request id: %s",
se.Code, se.Message, se.StatusCode, se.OpcRequestID)
}
func (se servicefailure) GetHTTPStatusCode() int {
return se.StatusCode
}
func (se servicefailure) GetMessage() string {
return se.Message
}
func (se servicefailure) GetCode() string {
return se.Code
}
func (se servicefailure) GetOpcRequestID() string {
return se.OpcRequestID
}
// IsServiceError returns false if the error is not service side, otherwise true
// additionally it returns an interface representing the ServiceError
func IsServiceError(err error) (failure ServiceError, ok bool) {
failure, ok = err.(servicefailure)
return
}
type deadlineExceededByBackoffError struct{}
func (deadlineExceededByBackoffError) Error() string {
return "now() + computed backoff duration exceeds request deadline"
}
// DeadlineExceededByBackoff is the error returned by Call() when GetNextDuration() returns a time.Duration that would
// force the user to wait past the request deadline before re-issuing a request. This enables us to exit early, since
// we cannot succeed based on the configured retry policy.
var DeadlineExceededByBackoff error = deadlineExceededByBackoffError{}

245
vendor/github.com/oracle/oci-go-sdk/common/helpers.go generated vendored Normal file
View File

@@ -0,0 +1,245 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package common
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
// String returns a pointer to the provided string
func String(value string) *string {
return &value
}
// Int returns a pointer to the provided int
func Int(value int) *int {
return &value
}
// Int64 returns a pointer to the provided int64
func Int64(value int64) *int64 {
return &value
}
// Uint returns a pointer to the provided uint
func Uint(value uint) *uint {
return &value
}
//Float32 returns a pointer to the provided float32
func Float32(value float32) *float32 {
return &value
}
//Float64 returns a pointer to the provided float64
func Float64(value float64) *float64 {
return &value
}
//Bool returns a pointer to the provided bool
func Bool(value bool) *bool {
return &value
}
//PointerString prints the values of pointers in a struct
//Producing a human friendly string for an struct with pointers.
//useful when debugging the values of a struct
func PointerString(datastruct interface{}) (representation string) {
val := reflect.ValueOf(datastruct)
typ := reflect.TypeOf(datastruct)
all := make([]string, 2)
all = append(all, "{")
for i := 0; i < typ.NumField(); i++ {
sf := typ.Field(i)
//unexported
if sf.PkgPath != "" && !sf.Anonymous {
continue
}
sv := val.Field(i)
stringValue := ""
if isNil(sv) {
stringValue = fmt.Sprintf("%s=<nil>", sf.Name)
} else {
if sv.Type().Kind() == reflect.Ptr {
sv = sv.Elem()
}
stringValue = fmt.Sprintf("%s=%v", sf.Name, sv)
}
all = append(all, stringValue)
}
all = append(all, "}")
representation = strings.TrimSpace(strings.Join(all, " "))
return
}
// SDKTime a struct that parses/renders to/from json using RFC339 date-time information
type SDKTime struct {
time.Time
}
// SDKDate a struct that parses/renders to/from json using only date information
type SDKDate struct {
//Date date information
Date time.Time
}
func sdkTimeFromTime(t time.Time) SDKTime {
return SDKTime{t}
}
func sdkDateFromTime(t time.Time) SDKDate {
return SDKDate{Date: t}
}
func formatTime(t SDKTime) string {
return t.Format(sdkTimeFormat)
}
func formatDate(t SDKDate) string {
return t.Date.Format(sdkDateFormat)
}
func now() *SDKTime {
t := SDKTime{time.Now()}
return &t
}
var timeType = reflect.TypeOf(SDKTime{})
var timeTypePtr = reflect.TypeOf(&SDKTime{})
var sdkDateType = reflect.TypeOf(SDKDate{})
var sdkDateTypePtr = reflect.TypeOf(&SDKDate{})
//Formats for sdk supported time representations
const sdkTimeFormat = time.RFC3339Nano
const rfc1123OptionalLeadingDigitsInDay = "Mon, _2 Jan 2006 15:04:05 MST"
const sdkDateFormat = "2006-01-02"
func tryParsingTimeWithValidFormatsForHeaders(data []byte, headerName string) (t time.Time, err error) {
header := strings.ToLower(headerName)
switch header {
case "lastmodified", "date":
t, err = tryParsing(data, time.RFC3339Nano, time.RFC3339, time.RFC1123, rfc1123OptionalLeadingDigitsInDay, time.RFC850, time.ANSIC)
return
default: //By default we parse with RFC3339
t, err = time.Parse(sdkTimeFormat, string(data))
return
}
}
func tryParsing(data []byte, layouts ...string) (tm time.Time, err error) {
datestring := string(data)
for _, l := range layouts {
tm, err = time.Parse(l, datestring)
if err == nil {
return
}
}
err = fmt.Errorf("Could not parse time: %s with formats: %s", datestring, layouts[:])
return
}
// String returns string representation of SDKDate
func (t *SDKDate) String() string {
return t.Date.Format(sdkDateFormat)
}
// NewSDKDateFromString parses the dateString into SDKDate
func NewSDKDateFromString(dateString string) (*SDKDate, error) {
parsedTime, err := time.Parse(sdkDateFormat, dateString)
if err != nil {
return nil, err
}
return &SDKDate{Date: parsedTime}, nil
}
// UnmarshalJSON unmarshals from json
func (t *SDKTime) UnmarshalJSON(data []byte) (e error) {
s := string(data)
if s == "null" {
t.Time = time.Time{}
} else {
//Try parsing with RFC3339
t.Time, e = time.Parse(`"`+sdkTimeFormat+`"`, string(data))
}
return
}
// MarshalJSON marshals to JSON
func (t *SDKTime) MarshalJSON() (buff []byte, e error) {
s := t.Format(sdkTimeFormat)
buff = []byte(`"` + s + `"`)
return
}
// UnmarshalJSON unmarshals from json
func (t *SDKDate) UnmarshalJSON(data []byte) (e error) {
if string(data) == `"null"` {
t.Date = time.Time{}
return
}
t.Date, e = tryParsing(data,
strconv.Quote(sdkDateFormat),
)
return
}
// MarshalJSON marshals to JSON
func (t *SDKDate) MarshalJSON() (buff []byte, e error) {
s := t.Date.Format(sdkDateFormat)
buff = []byte(strconv.Quote(s))
return
}
// PrivateKeyFromBytes is a helper function that will produce a RSA private
// key from bytes.
func PrivateKeyFromBytes(pemData []byte, password *string) (key *rsa.PrivateKey, e error) {
if pemBlock, _ := pem.Decode(pemData); pemBlock != nil {
decrypted := pemBlock.Bytes
if x509.IsEncryptedPEMBlock(pemBlock) {
if password == nil {
e = fmt.Errorf("private_key_password is required for encrypted private keys")
return
}
if decrypted, e = x509.DecryptPEMBlock(pemBlock, []byte(*password)); e != nil {
return
}
}
key, e = x509.ParsePKCS1PrivateKey(decrypted)
} else {
e = fmt.Errorf("PEM data was not found in buffer")
return
}
return
}
func generateRandUUID() (string, error) {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
return "", err
}
uuid := fmt.Sprintf("%x%x%x%x%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
return uuid, nil
}
func makeACopy(original []string) []string {
tmp := make([]string, len(original))
copy(tmp, original)
return tmp
}

971
vendor/github.com/oracle/oci-go-sdk/common/http.go generated vendored Normal file
View File

@@ -0,0 +1,971 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package common
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"time"
)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Request Marshaling
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
func isNil(v reflect.Value) bool {
return v.Kind() == reflect.Ptr && v.IsNil()
}
// Returns the string representation of a reflect.Value
// Only transforms primitive values
func toStringValue(v reflect.Value, field reflect.StructField) (string, error) {
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return "", fmt.Errorf("can not marshal a nil pointer")
}
v = v.Elem()
}
if v.Type() == timeType {
t := v.Interface().(SDKTime)
return formatTime(t), nil
}
if v.Type() == sdkDateType {
t := v.Interface().(SDKDate)
return formatDate(t), nil
}
switch v.Kind() {
case reflect.Bool:
return strconv.FormatBool(v.Bool()), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return strconv.FormatInt(v.Int(), 10), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return strconv.FormatUint(v.Uint(), 10), nil
case reflect.String:
return v.String(), nil
case reflect.Float32:
return strconv.FormatFloat(v.Float(), 'f', 6, 32), nil
case reflect.Float64:
return strconv.FormatFloat(v.Float(), 'f', 6, 64), nil
default:
return "", fmt.Errorf("marshaling structure to a http.Request does not support field named: %s of type: %v",
field.Name, v.Type().String())
}
}
func addBinaryBody(request *http.Request, value reflect.Value, field reflect.StructField) (e error) {
readCloser, ok := value.Interface().(io.ReadCloser)
isMandatory, err := strconv.ParseBool(field.Tag.Get("mandatory"))
if err != nil {
return fmt.Errorf("mandatory tag is not valid for field %s", field.Name)
}
if isMandatory && !ok {
e = fmt.Errorf("body of the request is mandatory and needs to be an io.ReadCloser interface. Can not marshal body of binary request")
return
}
request.Body = readCloser
//Set the default content type to application/octet-stream if not set
if request.Header.Get(requestHeaderContentType) == "" {
request.Header.Set(requestHeaderContentType, "application/octet-stream")
}
return nil
}
// getTaggedNilFieldNameOrError, evaluates if a field with json and non mandatory tags is nil
// returns the json tag name, or an error if the tags are incorrectly present
func getTaggedNilFieldNameOrError(field reflect.StructField, fieldValue reflect.Value) (bool, string, error) {
currentTag := field.Tag
jsonTag := currentTag.Get("json")
if jsonTag == "" {
return false, "", fmt.Errorf("json tag is not valid for field %s", field.Name)
}
partsJSONTag := strings.Split(jsonTag, ",")
nameJSONField := partsJSONTag[0]
if _, ok := currentTag.Lookup("mandatory"); !ok {
//No mandatory field set, no-op
return false, nameJSONField, nil
}
isMandatory, err := strconv.ParseBool(currentTag.Get("mandatory"))
if err != nil {
return false, "", fmt.Errorf("mandatory tag is not valid for field %s", field.Name)
}
// If the field is marked as mandatory, no-op
if isMandatory {
return false, nameJSONField, nil
}
Debugf("Adjusting tag: mandatory is false and json tag is valid on field: %s", field.Name)
// If the field can not be nil, then no-op
if !isNillableType(&fieldValue) {
Debugf("WARNING json field is tagged with mandatory flags, but the type can not be nil, field name: %s", field.Name)
return false, nameJSONField, nil
}
// If field value is nil, tag it as omitEmpty
return fieldValue.IsNil(), nameJSONField, nil
}
// isNillableType returns true if the filed can be nil
func isNillableType(value *reflect.Value) bool {
k := value.Kind()
switch k {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Slice:
return true
}
return false
}
// omitNilFieldsInJSON, removes json keys whose struct value is nil, and the field is tagged with the json and
// mandatory:false tags
func omitNilFieldsInJSON(data interface{}, value reflect.Value) (interface{}, error) {
switch value.Kind() {
case reflect.Struct:
jsonMap := data.(map[string]interface{})
fieldType := value.Type()
for i := 0; i < fieldType.NumField(); i++ {
currentField := fieldType.Field(i)
//unexported skip
if currentField.PkgPath != "" {
continue
}
//Does not have json tag, no-op
if _, ok := currentField.Tag.Lookup("json"); !ok {
continue
}
currentFieldValue := value.Field(i)
ok, jsonFieldName, err := getTaggedNilFieldNameOrError(currentField, currentFieldValue)
if err != nil {
return nil, fmt.Errorf("can not omit nil fields for field: %s, due to: %s",
currentField.Name, err.Error())
}
//Delete the struct field from the json representation
if ok {
delete(jsonMap, jsonFieldName)
continue
}
// Check to make sure the field is part of the json representation of the value
if _, contains := jsonMap[jsonFieldName]; !contains {
Debugf("Field %s is not present in json, omitting", jsonFieldName)
continue
}
if currentFieldValue.Type() == timeType || currentFieldValue.Type() == timeTypePtr ||
currentField.Type == sdkDateType || currentField.Type == sdkDateTypePtr {
continue
}
// does it need to be adjusted?
var adjustedValue interface{}
adjustedValue, err = omitNilFieldsInJSON(jsonMap[jsonFieldName], currentFieldValue)
if err != nil {
return nil, fmt.Errorf("can not omit nil fields for field: %s, due to: %s",
currentField.Name, err.Error())
}
jsonMap[jsonFieldName] = adjustedValue
}
return jsonMap, nil
case reflect.Slice, reflect.Array:
// Special case: a []byte may have been marshalled as a string
if data != nil && reflect.TypeOf(data).Kind() == reflect.String && value.Type().Elem().Kind() == reflect.Uint8 {
return data, nil
}
jsonList, ok := data.([]interface{})
if !ok {
return nil, fmt.Errorf("can not omit nil fields, data was expected to be a not-nil list")
}
newList := make([]interface{}, len(jsonList))
var err error
for i, val := range jsonList {
newList[i], err = omitNilFieldsInJSON(val, value.Index(i))
if err != nil {
return nil, err
}
}
return newList, nil
case reflect.Map:
jsonMap, ok := data.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("can not omit nil fields, data was expected to be a not-nil map")
}
newMap := make(map[string]interface{}, len(jsonMap))
var err error
for key, val := range jsonMap {
newMap[key], err = omitNilFieldsInJSON(val, value.MapIndex(reflect.ValueOf(key)))
if err != nil {
return nil, err
}
}
return newMap, nil
case reflect.Ptr, reflect.Interface:
valPtr := value.Elem()
return omitNilFieldsInJSON(data, valPtr)
default:
//Otherwise no-op
return data, nil
}
}
// removeNilFieldsInJSONWithTaggedStruct remove struct fields tagged with json and mandatory false
// that are nil
func removeNilFieldsInJSONWithTaggedStruct(rawJSON []byte, value reflect.Value) ([]byte, error) {
var rawInterface interface{}
decoder := json.NewDecoder(bytes.NewBuffer(rawJSON))
decoder.UseNumber()
var err error
if err = decoder.Decode(&rawInterface); err != nil {
return nil, err
}
fixedMap, err := omitNilFieldsInJSON(rawInterface, value)
if err != nil {
return nil, err
}
return json.Marshal(fixedMap)
}
func addToBody(request *http.Request, value reflect.Value, field reflect.StructField) (e error) {
Debugln("Marshaling to body from field:", field.Name)
if request.Body != nil {
Logf("The body of the request is already set. Structure: %s will overwrite it\n", field.Name)
}
tag := field.Tag
encoding := tag.Get("encoding")
if encoding == "binary" {
return addBinaryBody(request, value, field)
}
rawJSON, e := json.Marshal(value.Interface())
if e != nil {
return
}
marshaled, e := removeNilFieldsInJSONWithTaggedStruct(rawJSON, value)
if e != nil {
return
}
if defaultLogger.LogLevel() == verboseLogging {
Debugf("Marshaled body is: %s\n", string(marshaled))
}
bodyBytes := bytes.NewReader(marshaled)
request.ContentLength = int64(bodyBytes.Len())
request.Header.Set(requestHeaderContentLength, strconv.FormatInt(request.ContentLength, 10))
request.Header.Set(requestHeaderContentType, "application/json")
request.Body = ioutil.NopCloser(bodyBytes)
request.GetBody = func() (io.ReadCloser, error) {
return ioutil.NopCloser(bodyBytes), nil
}
return
}
func addToQuery(request *http.Request, value reflect.Value, field reflect.StructField) (e error) {
Debugln("Marshaling to query from field: ", field.Name)
if request.URL == nil {
request.URL = &url.URL{}
}
query := request.URL.Query()
var queryParameterValue, queryParameterName string
if queryParameterName = field.Tag.Get("name"); queryParameterName == "" {
return fmt.Errorf("marshaling request to a query requires the 'name' tag for field: %s ", field.Name)
}
mandatory, _ := strconv.ParseBool(strings.ToLower(field.Tag.Get("mandatory")))
//If mandatory and nil. Error out
if mandatory && isNil(value) {
return fmt.Errorf("marshaling request to a header requires not nil pointer for field: %s", field.Name)
}
//if not mandatory and nil. Omit
if !mandatory && isNil(value) {
Debugf("Query parameter value is not mandatory and is nil pointer in field: %s. Skipping query", field.Name)
return
}
encoding := strings.ToLower(field.Tag.Get("collectionFormat"))
var collectionFormatStringValues []string
switch encoding {
case "csv", "multi":
if value.Kind() != reflect.Slice && value.Kind() != reflect.Array {
e = fmt.Errorf("query parameter is tagged as csv or multi yet its type is neither an Array nor a Slice: %s", field.Name)
break
}
numOfElements := value.Len()
collectionFormatStringValues = make([]string, numOfElements)
for i := 0; i < numOfElements; i++ {
collectionFormatStringValues[i], e = toStringValue(value.Index(i), field)
if e != nil {
break
}
}
queryParameterValue = strings.Join(collectionFormatStringValues, ",")
case "":
queryParameterValue, e = toStringValue(value, field)
default:
e = fmt.Errorf("encoding of type %s is not supported for query param: %s", encoding, field.Name)
}
if e != nil {
return
}
//check for tag "omitEmpty", this is done to accomodate unset fields that do not
//support an empty string: enums in query params
if omitEmpty, present := field.Tag.Lookup("omitEmpty"); present {
omitEmptyBool, _ := strconv.ParseBool(strings.ToLower(omitEmpty))
if queryParameterValue != "" || !omitEmptyBool {
addToQueryForEncoding(&query, encoding, queryParameterName, queryParameterValue, collectionFormatStringValues)
} else {
Debugf("Omitting %s, is empty and omitEmpty tag is set", field.Name)
}
} else {
addToQueryForEncoding(&query, encoding, queryParameterName, queryParameterValue, collectionFormatStringValues)
}
request.URL.RawQuery = query.Encode()
return
}
func addToQueryForEncoding(query *url.Values, encoding string, queryParameterName string, queryParameterValue string, collectionFormatStringValues []string) {
if encoding == "multi" {
for _, stringValue := range collectionFormatStringValues {
query.Add(queryParameterName, stringValue)
}
} else {
query.Set(queryParameterName, queryParameterValue)
}
}
// Adds to the path of the url in the order they appear in the structure
func addToPath(request *http.Request, value reflect.Value, field reflect.StructField) (e error) {
var additionalURLPathPart string
if additionalURLPathPart, e = toStringValue(value, field); e != nil {
return fmt.Errorf("can not marshal to path in request for field %s. Due to %s", field.Name, e.Error())
}
// path should not be empty for any operations
if len(additionalURLPathPart) == 0 {
return fmt.Errorf("value cannot be empty for field %s in path", field.Name)
}
if request.URL == nil {
request.URL = &url.URL{}
request.URL.Path = ""
}
var currentURLPath = request.URL.Path
var templatedPathRegex, _ = regexp.Compile(".*{.+}.*")
if !templatedPathRegex.MatchString(currentURLPath) {
Debugln("Marshaling request to path by appending field:", field.Name)
allPath := []string{currentURLPath, additionalURLPathPart}
request.URL.Path = strings.Join(allPath, "/")
} else {
var fieldName string
if fieldName = field.Tag.Get("name"); fieldName == "" {
e = fmt.Errorf("marshaling request to path name and template requires a 'name' tag for field: %s", field.Name)
return
}
urlTemplate := currentURLPath
Debugln("Marshaling to path from field: ", field.Name, " in template: ", urlTemplate)
request.URL.Path = strings.Replace(urlTemplate, "{"+fieldName+"}", additionalURLPathPart, -1)
}
return
}
func setWellKnownHeaders(request *http.Request, headerName, headerValue string) (e error) {
switch strings.ToLower(headerName) {
case "content-length":
var len int
len, e = strconv.Atoi(headerValue)
if e != nil {
return
}
request.ContentLength = int64(len)
}
return nil
}
func addToHeader(request *http.Request, value reflect.Value, field reflect.StructField) (e error) {
Debugln("Marshaling to header from field: ", field.Name)
if request.Header == nil {
request.Header = http.Header{}
}
var headerName, headerValue string
if headerName = field.Tag.Get("name"); headerName == "" {
return fmt.Errorf("marshaling request to a header requires the 'name' tag for field: %s", field.Name)
}
mandatory, _ := strconv.ParseBool(strings.ToLower(field.Tag.Get("mandatory")))
//If mandatory and nil. Error out
if mandatory && isNil(value) {
return fmt.Errorf("marshaling request to a header requires not nil pointer for field: %s", field.Name)
}
// generate opc-request-id if header value is nil and header name matches
value = generateOpcRequestID(headerName, value)
//if not mandatory and nil. Omit
if !mandatory && isNil(value) {
Debugf("Header value is not mandatory and is nil pointer in field: %s. Skipping header", field.Name)
return
}
//Otherwise get value and set header
if headerValue, e = toStringValue(value, field); e != nil {
return
}
if e = setWellKnownHeaders(request, headerName, headerValue); e != nil {
return
}
request.Header.Add(headerName, headerValue)
return
}
// Header collection is a map of string to string that gets rendered as individual headers with a given prefix
func addToHeaderCollection(request *http.Request, value reflect.Value, field reflect.StructField) (e error) {
Debugln("Marshaling to header-collection from field:", field.Name)
if request.Header == nil {
request.Header = http.Header{}
}
var headerPrefix string
if headerPrefix = field.Tag.Get("prefix"); headerPrefix == "" {
return fmt.Errorf("marshaling request to a header requires the 'prefix' tag for field: %s", field.Name)
}
mandatory, _ := strconv.ParseBool(strings.ToLower(field.Tag.Get("mandatory")))
//If mandatory and nil. Error out
if mandatory && isNil(value) {
return fmt.Errorf("marshaling request to a header requires not nil pointer for field: %s", field.Name)
}
//if not mandatory and nil. Omit
if !mandatory && isNil(value) {
Debugf("Header value is not mandatory and is nil pointer in field: %s. Skipping header", field.Name)
return
}
//cast to map
headerValues, ok := value.Interface().(map[string]string)
if !ok {
e = fmt.Errorf("header fields need to be of type map[string]string")
return
}
for k, v := range headerValues {
headerName := fmt.Sprintf("%s%s", headerPrefix, k)
request.Header.Set(headerName, v)
}
return
}
// Makes sure the incoming structure is able to be marshalled
// to a request
func checkForValidRequestStruct(s interface{}) (*reflect.Value, error) {
val := reflect.ValueOf(s)
for val.Kind() == reflect.Ptr {
if val.IsNil() {
return nil, fmt.Errorf("can not marshal to request a pointer to structure")
}
val = val.Elem()
}
if s == nil {
return nil, fmt.Errorf("can not marshal to request a nil structure")
}
if val.Kind() != reflect.Struct {
return nil, fmt.Errorf("can not marshal to request, expects struct input. Got %v", val.Kind())
}
return &val, nil
}
// Populates the parts of a request by reading tags in the passed structure
// nested structs are followed recursively depth-first.
func structToRequestPart(request *http.Request, val reflect.Value) (err error) {
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
if err != nil {
return
}
sf := typ.Field(i)
//unexported
if sf.PkgPath != "" && !sf.Anonymous {
continue
}
sv := val.Field(i)
tag := sf.Tag.Get("contributesTo")
switch tag {
case "header":
err = addToHeader(request, sv, sf)
case "header-collection":
err = addToHeaderCollection(request, sv, sf)
case "path":
err = addToPath(request, sv, sf)
case "query":
err = addToQuery(request, sv, sf)
case "body":
err = addToBody(request, sv, sf)
case "":
Debugln(sf.Name, " does not contain contributes tag. Skipping.")
default:
err = fmt.Errorf("can not marshal field: %s. It needs to contain valid contributesTo tag", sf.Name)
}
}
//If headers are and the content type was not set, we default to application/json
if request.Header != nil && request.Header.Get(requestHeaderContentType) == "" {
request.Header.Set(requestHeaderContentType, "application/json")
}
return
}
// HTTPRequestMarshaller marshals a structure to an http request using tag values in the struct
// The marshaller tag should like the following
// type A struct {
// ANumber string `contributesTo="query" name="number"`
// TheBody `contributesTo="body"`
// }
// where the contributesTo tag can be: header, path, query, body
// and the 'name' tag is the name of the value used in the http request(not applicable for path)
// If path is specified as part of the tag, the values are appened to the url path
// in the order they appear in the structure
// The current implementation only supports primitive types, except for the body tag, which needs a struct type.
// The body of a request will be marshaled using the tags of the structure
func HTTPRequestMarshaller(requestStruct interface{}, httpRequest *http.Request) (err error) {
var val *reflect.Value
if val, err = checkForValidRequestStruct(requestStruct); err != nil {
return
}
Debugln("Marshaling to Request: ", val.Type().Name())
err = structToRequestPart(httpRequest, *val)
return
}
// MakeDefaultHTTPRequest creates the basic http request with the necessary headers set
func MakeDefaultHTTPRequest(method, path string) (httpRequest http.Request) {
httpRequest = http.Request{
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
URL: &url.URL{},
}
httpRequest.Header.Set(requestHeaderContentLength, "0")
httpRequest.Header.Set(requestHeaderDate, time.Now().UTC().Format(http.TimeFormat))
httpRequest.Header.Set(requestHeaderOpcClientInfo, strings.Join([]string{defaultSDKMarker, Version()}, "/"))
httpRequest.Header.Set(requestHeaderAccept, "*/*")
httpRequest.Method = method
httpRequest.URL.Path = path
return
}
// MakeDefaultHTTPRequestWithTaggedStruct creates an http request from an struct with tagged fields, see HTTPRequestMarshaller
// for more information
func MakeDefaultHTTPRequestWithTaggedStruct(method, path string, requestStruct interface{}) (httpRequest http.Request, err error) {
httpRequest = MakeDefaultHTTPRequest(method, path)
err = HTTPRequestMarshaller(requestStruct, &httpRequest)
return
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Request UnMarshaling
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Makes sure the incoming structure is able to be unmarshaled
// to a request
func checkForValidResponseStruct(s interface{}) (*reflect.Value, error) {
val := reflect.ValueOf(s)
for val.Kind() == reflect.Ptr {
if val.IsNil() {
return nil, fmt.Errorf("can not unmarshal to response a pointer to nil structure")
}
val = val.Elem()
}
if s == nil {
return nil, fmt.Errorf("can not unmarshal to response a nil structure")
}
if val.Kind() != reflect.Struct {
return nil, fmt.Errorf("can not unmarshal to response, expects struct input. Got %v", val.Kind())
}
return &val, nil
}
func intSizeFromKind(kind reflect.Kind) int {
switch kind {
case reflect.Int8, reflect.Uint8:
return 8
case reflect.Int16, reflect.Uint16:
return 16
case reflect.Int32, reflect.Uint32:
return 32
case reflect.Int64, reflect.Uint64:
return 64
case reflect.Int, reflect.Uint:
return strconv.IntSize
default:
Debugf("The type is not valid: %v. Returing int size for arch\n", kind.String())
return strconv.IntSize
}
}
func analyzeValue(stringValue string, kind reflect.Kind, field reflect.StructField) (val reflect.Value, valPointer reflect.Value, err error) {
switch kind {
case timeType.Kind():
var t time.Time
t, err = tryParsingTimeWithValidFormatsForHeaders([]byte(stringValue), field.Name)
if err != nil {
return
}
sdkTime := sdkTimeFromTime(t)
val = reflect.ValueOf(sdkTime)
valPointer = reflect.ValueOf(&sdkTime)
return
case sdkDateType.Kind():
var t time.Time
t, err = tryParsingTimeWithValidFormatsForHeaders([]byte(stringValue), field.Name)
if err != nil {
return
}
sdkDate := sdkDateFromTime(t)
val = reflect.ValueOf(sdkDate)
valPointer = reflect.ValueOf(&sdkDate)
return
case reflect.Bool:
var bVal bool
if bVal, err = strconv.ParseBool(stringValue); err != nil {
return
}
val = reflect.ValueOf(bVal)
valPointer = reflect.ValueOf(&bVal)
return
case reflect.Int:
size := intSizeFromKind(kind)
var iVal int64
if iVal, err = strconv.ParseInt(stringValue, 10, size); err != nil {
return
}
var iiVal int
iiVal = int(iVal)
val = reflect.ValueOf(iiVal)
valPointer = reflect.ValueOf(&iiVal)
return
case reflect.Int64:
size := intSizeFromKind(kind)
var iVal int64
if iVal, err = strconv.ParseInt(stringValue, 10, size); err != nil {
return
}
val = reflect.ValueOf(iVal)
valPointer = reflect.ValueOf(&iVal)
return
case reflect.Uint:
size := intSizeFromKind(kind)
var iVal uint64
if iVal, err = strconv.ParseUint(stringValue, 10, size); err != nil {
return
}
var uiVal uint
uiVal = uint(iVal)
val = reflect.ValueOf(uiVal)
valPointer = reflect.ValueOf(&uiVal)
return
case reflect.String:
val = reflect.ValueOf(stringValue)
valPointer = reflect.ValueOf(&stringValue)
case reflect.Float32:
var fVal float64
if fVal, err = strconv.ParseFloat(stringValue, 32); err != nil {
return
}
var ffVal float32
ffVal = float32(fVal)
val = reflect.ValueOf(ffVal)
valPointer = reflect.ValueOf(&ffVal)
return
case reflect.Float64:
var fVal float64
if fVal, err = strconv.ParseFloat(stringValue, 64); err != nil {
return
}
val = reflect.ValueOf(fVal)
valPointer = reflect.ValueOf(&fVal)
return
default:
err = fmt.Errorf("value for kind: %s not supported", kind)
}
return
}
// Sets the field of a struct, with the appropiate value of the string
// Only sets basic types
func fromStringValue(newValue string, val *reflect.Value, field reflect.StructField) (err error) {
if !val.CanSet() {
err = fmt.Errorf("can not set field name: %s of type: %v", field.Name, val.Type().String())
return
}
kind := val.Kind()
isPointer := false
if val.Kind() == reflect.Ptr {
isPointer = true
kind = field.Type.Elem().Kind()
}
value, valPtr, err := analyzeValue(newValue, kind, field)
if err != nil {
return
}
if !isPointer {
val.Set(value)
} else {
val.Set(valPtr)
}
return
}
// PolymorphicJSONUnmarshaler is the interface to unmarshal polymorphic json payloads
type PolymorphicJSONUnmarshaler interface {
UnmarshalPolymorphicJSON(data []byte) (interface{}, error)
}
func valueFromPolymorphicJSON(content []byte, unmarshaler PolymorphicJSONUnmarshaler) (val interface{}, err error) {
err = json.Unmarshal(content, unmarshaler)
if err != nil {
return
}
val, err = unmarshaler.UnmarshalPolymorphicJSON(content)
return
}
func valueFromJSONBody(response *http.Response, value *reflect.Value, unmarshaler PolymorphicJSONUnmarshaler) (val interface{}, err error) {
//Consumes the body, consider implementing it
//without body consumption
var content []byte
content, err = ioutil.ReadAll(response.Body)
if err != nil {
return
}
if unmarshaler != nil {
val, err = valueFromPolymorphicJSON(content, unmarshaler)
return
}
val = reflect.New(value.Type()).Interface()
err = json.Unmarshal(content, &val)
return
}
func addFromBody(response *http.Response, value *reflect.Value, field reflect.StructField, unmarshaler PolymorphicJSONUnmarshaler) (err error) {
Debugln("Unmarshaling from body to field: ", field.Name)
if response.Body == nil {
Debugln("Unmarshaling body skipped due to nil body content for field: ", field.Name)
return nil
}
tag := field.Tag
encoding := tag.Get("encoding")
var iVal interface{}
switch encoding {
case "binary":
value.Set(reflect.ValueOf(response.Body))
return
case "plain-text":
//Expects UTF-8
byteArr, e := ioutil.ReadAll(response.Body)
if e != nil {
return e
}
str := string(byteArr)
value.Set(reflect.ValueOf(&str))
return
default: //If the encoding is not set. we'll decode with json
iVal, err = valueFromJSONBody(response, value, unmarshaler)
if err != nil {
return
}
newVal := reflect.ValueOf(iVal)
if newVal.Kind() == reflect.Ptr {
newVal = newVal.Elem()
}
value.Set(newVal)
return
}
}
func addFromHeader(response *http.Response, value *reflect.Value, field reflect.StructField) (err error) {
Debugln("Unmarshaling from header to field: ", field.Name)
var headerName string
if headerName = field.Tag.Get("name"); headerName == "" {
return fmt.Errorf("unmarshaling response to a header requires the 'name' tag for field: %s", field.Name)
}
headerValue := response.Header.Get(headerName)
if headerValue == "" {
Debugf("Unmarshalling did not find header with name:%s", headerName)
return nil
}
if err = fromStringValue(headerValue, value, field); err != nil {
return fmt.Errorf("unmarshaling response to a header failed for field %s, due to %s", field.Name,
err.Error())
}
return
}
func addFromHeaderCollection(response *http.Response, value *reflect.Value, field reflect.StructField) error {
Debugln("Unmarshaling from header-collection to field:", field.Name)
var headerPrefix string
if headerPrefix = field.Tag.Get("prefix"); headerPrefix == "" {
return fmt.Errorf("Unmarshaling response to a header-collection requires the 'prefix' tag for field: %s", field.Name)
}
mapCollection := make(map[string]string)
for name, value := range response.Header {
nameLowerCase := strings.ToLower(name)
if strings.HasPrefix(nameLowerCase, headerPrefix) {
headerNoPrefix := strings.TrimPrefix(nameLowerCase, headerPrefix)
mapCollection[headerNoPrefix] = value[0]
}
}
Debugln("Marshalled header collection is:", mapCollection)
value.Set(reflect.ValueOf(mapCollection))
return nil
}
// Populates a struct from parts of a request by reading tags of the struct
func responseToStruct(response *http.Response, val *reflect.Value, unmarshaler PolymorphicJSONUnmarshaler) (err error) {
typ := val.Type()
for i := 0; i < typ.NumField(); i++ {
if err != nil {
return
}
sf := typ.Field(i)
//unexported
if sf.PkgPath != "" {
continue
}
sv := val.Field(i)
tag := sf.Tag.Get("presentIn")
switch tag {
case "header":
err = addFromHeader(response, &sv, sf)
case "header-collection":
err = addFromHeaderCollection(response, &sv, sf)
case "body":
err = addFromBody(response, &sv, sf, unmarshaler)
case "":
Debugln(sf.Name, " does not contain presentIn tag. Skipping")
default:
err = fmt.Errorf("can not unmarshal field: %s. It needs to contain valid presentIn tag", sf.Name)
}
}
return
}
// UnmarshalResponse hydrates the fields of a struct with the values of a http response, guided
// by the field tags. The directive tag is "presentIn" and it can be either
// - "header": Will look for the header tagged as "name" in the headers of the struct and set it value to that
// - "body": It will try to marshal the body from a json string to a struct tagged with 'presentIn: "body"'.
// Further this method will consume the body it should be safe to close it after this function
// Notice the current implementation only supports native types:int, strings, floats, bool as the field types
func UnmarshalResponse(httpResponse *http.Response, responseStruct interface{}) (err error) {
var val *reflect.Value
if val, err = checkForValidResponseStruct(responseStruct); err != nil {
return
}
if err = responseToStruct(httpResponse, val, nil); err != nil {
return
}
return nil
}
// UnmarshalResponseWithPolymorphicBody similar to UnmarshalResponse but assumes the body of the response
// contains polymorphic json. This function will use the unmarshaler argument to unmarshal json content
func UnmarshalResponseWithPolymorphicBody(httpResponse *http.Response, responseStruct interface{}, unmarshaler PolymorphicJSONUnmarshaler) (err error) {
var val *reflect.Value
if val, err = checkForValidResponseStruct(responseStruct); err != nil {
return
}
if err = responseToStruct(httpResponse, val, unmarshaler); err != nil {
return
}
return nil
}
// generate request id if user not provided and for each retry operation re-gen a new request id
func generateOpcRequestID(headerName string, value reflect.Value) (newValue reflect.Value) {
newValue = value
isNilValue := isNil(newValue)
isOpcRequestIDHeader := headerName == requestHeaderOpcRequestID || headerName == requestHeaderOpcClientRequestID
if isNilValue && isOpcRequestIDHeader {
requestID, err := generateRandUUID()
if err != nil {
// this will not fail the request, just skip add opc-request-id
Debugf("unable to generate opc-request-id. %s", err.Error())
} else {
newValue = reflect.ValueOf(String(requestID))
Debugf("add request id for header: %s, with value: %s", headerName, requestID)
}
}
return
}

View File

@@ -0,0 +1,269 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package common
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
)
// HTTPRequestSigner the interface to sign a request
type HTTPRequestSigner interface {
Sign(r *http.Request) error
}
// KeyProvider interface that wraps information about the key's account owner
type KeyProvider interface {
PrivateRSAKey() (*rsa.PrivateKey, error)
KeyID() (string, error)
}
const signerVersion = "1"
// SignerBodyHashPredicate a function that allows to disable/enable body hashing
// of requests and headers associated with body content
type SignerBodyHashPredicate func(r *http.Request) bool
// ociRequestSigner implements the http-signatures-draft spec
// as described in https://tools.ietf.org/html/draft-cavage-http-signatures-08
type ociRequestSigner struct {
KeyProvider KeyProvider
GenericHeaders []string
BodyHeaders []string
ShouldHashBody SignerBodyHashPredicate
}
var (
defaultGenericHeaders = []string{"date", "(request-target)", "host"}
defaultBodyHeaders = []string{"content-length", "content-type", "x-content-sha256"}
defaultBodyHashPredicate = func(r *http.Request) bool {
return r.Method == http.MethodPost || r.Method == http.MethodPut || r.Method == http.MethodPatch
}
)
// DefaultGenericHeaders list of default generic headers that is used in signing
func DefaultGenericHeaders() []string {
return makeACopy(defaultGenericHeaders)
}
// DefaultBodyHeaders list of default body headers that is used in signing
func DefaultBodyHeaders() []string {
return makeACopy(defaultBodyHeaders)
}
// DefaultRequestSigner creates a signer with default parameters.
func DefaultRequestSigner(provider KeyProvider) HTTPRequestSigner {
return RequestSigner(provider, defaultGenericHeaders, defaultBodyHeaders)
}
// RequestSignerExcludeBody creates a signer without hash the body.
func RequestSignerExcludeBody(provider KeyProvider) HTTPRequestSigner {
bodyHashPredicate := func(r *http.Request) bool {
// week request signer will not hash the body
return false
}
return RequestSignerWithBodyHashingPredicate(provider, defaultGenericHeaders, defaultBodyHeaders, bodyHashPredicate)
}
// NewSignerFromOCIRequestSigner creates a copy of the request signer and attaches the new SignerBodyHashPredicate
// returns an error if the passed signer is not of type ociRequestSigner
func NewSignerFromOCIRequestSigner(oldSigner HTTPRequestSigner, predicate SignerBodyHashPredicate) (HTTPRequestSigner, error) {
if oldS, ok := oldSigner.(ociRequestSigner); ok {
s := ociRequestSigner{
KeyProvider: oldS.KeyProvider,
GenericHeaders: oldS.GenericHeaders,
BodyHeaders: oldS.BodyHeaders,
ShouldHashBody: predicate,
}
return s, nil
}
return nil, fmt.Errorf("can not create a signer, input signer needs to be of type ociRequestSigner")
}
// RequestSigner creates a signer that utilizes the specified headers for signing
// and the default predicate for using the body of the request as part of the signature
func RequestSigner(provider KeyProvider, genericHeaders, bodyHeaders []string) HTTPRequestSigner {
return ociRequestSigner{
KeyProvider: provider,
GenericHeaders: genericHeaders,
BodyHeaders: bodyHeaders,
ShouldHashBody: defaultBodyHashPredicate}
}
// RequestSignerWithBodyHashingPredicate creates a signer that utilizes the specified headers for signing, as well as a predicate for using
// the body of the request and bodyHeaders parameter as part of the signature
func RequestSignerWithBodyHashingPredicate(provider KeyProvider, genericHeaders, bodyHeaders []string, shouldHashBody SignerBodyHashPredicate) HTTPRequestSigner {
return ociRequestSigner{
KeyProvider: provider,
GenericHeaders: genericHeaders,
BodyHeaders: bodyHeaders,
ShouldHashBody: shouldHashBody}
}
func (signer ociRequestSigner) getSigningHeaders(r *http.Request) []string {
var result []string
result = append(result, signer.GenericHeaders...)
if signer.ShouldHashBody(r) {
result = append(result, signer.BodyHeaders...)
}
return result
}
func (signer ociRequestSigner) getSigningString(request *http.Request) string {
signingHeaders := signer.getSigningHeaders(request)
signingParts := make([]string, len(signingHeaders))
for i, part := range signingHeaders {
var value string
part = strings.ToLower(part)
switch part {
case "(request-target)":
value = getRequestTarget(request)
case "host":
value = request.URL.Host
if len(value) == 0 {
value = request.Host
}
default:
value = request.Header.Get(part)
}
signingParts[i] = fmt.Sprintf("%s: %s", part, value)
}
signingString := strings.Join(signingParts, "\n")
return signingString
}
func getRequestTarget(request *http.Request) string {
lowercaseMethod := strings.ToLower(request.Method)
return fmt.Sprintf("%s %s", lowercaseMethod, request.URL.RequestURI())
}
func calculateHashOfBody(request *http.Request) (err error) {
var hash string
hash, err = GetBodyHash(request)
if err != nil {
return
}
request.Header.Set(requestHeaderXContentSHA256, hash)
return
}
// drainBody reads all of b to memory and then returns two equivalent
// ReadClosers yielding the same bytes.
//
// It returns an error if the initial slurp of all bytes fails. It does not attempt
// to make the returned ReadClosers have identical error-matching behavior.
func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
if b == http.NoBody {
// No copying needed. Preserve the magic sentinel meaning of NoBody.
return http.NoBody, http.NoBody, nil
}
var buf bytes.Buffer
if _, err = buf.ReadFrom(b); err != nil {
return nil, b, err
}
if err = b.Close(); err != nil {
return nil, b, err
}
return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
}
func hashAndEncode(data []byte) string {
hashedContent := sha256.Sum256(data)
hash := base64.StdEncoding.EncodeToString(hashedContent[:])
return hash
}
// GetBodyHash creates a base64 string from the hash of body the request
func GetBodyHash(request *http.Request) (hashString string, err error) {
if request.Body == nil {
request.ContentLength = 0
request.Header.Set(requestHeaderContentLength, fmt.Sprintf("%v", request.ContentLength))
return hashAndEncode([]byte("")), nil
}
var data []byte
bReader := request.Body
bReader, request.Body, err = drainBody(request.Body)
if err != nil {
return "", fmt.Errorf("can not read body of request while calculating body hash: %s", err.Error())
}
data, err = ioutil.ReadAll(bReader)
if err != nil {
return "", fmt.Errorf("can not read body of request while calculating body hash: %s", err.Error())
}
// Since the request can be coming from a binary body. Make an attempt to set the body length
request.ContentLength = int64(len(data))
request.Header.Set(requestHeaderContentLength, fmt.Sprintf("%v", request.ContentLength))
hashString = hashAndEncode(data)
return
}
func (signer ociRequestSigner) computeSignature(request *http.Request) (signature string, err error) {
signingString := signer.getSigningString(request)
hasher := sha256.New()
hasher.Write([]byte(signingString))
hashed := hasher.Sum(nil)
privateKey, err := signer.KeyProvider.PrivateRSAKey()
if err != nil {
return
}
var unencodedSig []byte
unencodedSig, e := rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed)
if e != nil {
err = fmt.Errorf("can not compute signature while signing the request %s: ", e.Error())
return
}
signature = base64.StdEncoding.EncodeToString(unencodedSig)
return
}
// Sign signs the http request, by inspecting the necessary headers. Once signed
// the request will have the proper 'Authorization' header set, otherwise
// and error is returned
func (signer ociRequestSigner) Sign(request *http.Request) (err error) {
if signer.ShouldHashBody(request) {
err = calculateHashOfBody(request)
if err != nil {
return
}
}
var signature string
if signature, err = signer.computeSignature(request); err != nil {
return
}
signingHeaders := strings.Join(signer.getSigningHeaders(request), " ")
var keyID string
if keyID, err = signer.KeyProvider.KeyID(); err != nil {
return
}
authValue := fmt.Sprintf("Signature version=\"%s\",headers=\"%s\",keyId=\"%s\",algorithm=\"rsa-sha256\",signature=\"%s\"",
signerVersion, signingHeaders, keyID, signature)
request.Header.Set(requestHeaderAuthorization, authValue)
return
}

170
vendor/github.com/oracle/oci-go-sdk/common/log.go generated vendored Normal file
View File

@@ -0,0 +1,170 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package common
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"sync"
)
//sdkLogger an interface for logging in the SDK
type sdkLogger interface {
//LogLevel returns the log level of sdkLogger
LogLevel() int
//Log logs v with the provided format if the current log level is loglevel
Log(logLevel int, format string, v ...interface{}) error
}
//noLogging no logging messages
const noLogging = 0
//infoLogging minimal logging messages
const infoLogging = 1
//debugLogging some logging messages
const debugLogging = 2
//verboseLogging all logging messages
const verboseLogging = 3
//defaultSDKLogger the default implementation of the sdkLogger
type defaultSDKLogger struct {
currentLoggingLevel int
verboseLogger *log.Logger
debugLogger *log.Logger
infoLogger *log.Logger
nullLogger *log.Logger
}
//defaultLogger is the defaultLogger in the SDK
var defaultLogger sdkLogger
var loggerLock sync.Mutex
//initializes the SDK defaultLogger as a defaultLogger
func init() {
l, _ := newSDKLogger()
setSDKLogger(l)
}
//setSDKLogger sets the logger used by the sdk
func setSDKLogger(logger sdkLogger) {
loggerLock.Lock()
defaultLogger = logger
loggerLock.Unlock()
}
// newSDKLogger creates a defaultSDKLogger
// Debug logging is turned on/off by the presence of the environment variable "OCI_GO_SDK_DEBUG"
// The value of the "OCI_GO_SDK_DEBUG" environment variable controls the logging level.
// "null" outputs no log messages
// "i" or "info" outputs minimal log messages
// "d" or "debug" outputs some logs messages
// "v" or "verbose" outputs all logs messages, including body of requests
func newSDKLogger() (defaultSDKLogger, error) {
logger := defaultSDKLogger{}
logger.currentLoggingLevel = noLogging
logger.verboseLogger = log.New(os.Stderr, "VERBOSE ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
logger.debugLogger = log.New(os.Stderr, "DEBUG ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
logger.infoLogger = log.New(os.Stderr, "INFO ", log.Ldate|log.Lmicroseconds|log.Lshortfile)
logger.nullLogger = log.New(ioutil.Discard, "", log.Ldate|log.Lmicroseconds|log.Lshortfile)
configured, isLogEnabled := os.LookupEnv("OCI_GO_SDK_DEBUG")
// If env variable not present turn logging of
if !isLogEnabled {
logger.currentLoggingLevel = noLogging
} else {
switch strings.ToLower(configured) {
case "null":
logger.currentLoggingLevel = noLogging
break
case "i", "info":
logger.currentLoggingLevel = infoLogging
break
case "d", "debug":
logger.currentLoggingLevel = debugLogging
break
//1 here for backwards compatibility
case "v", "verbose", "1":
logger.currentLoggingLevel = verboseLogging
break
default:
logger.currentLoggingLevel = infoLogging
}
logger.infoLogger.Println("logger level set to: ", logger.currentLoggingLevel)
}
return logger, nil
}
func (l defaultSDKLogger) getLoggerForLevel(logLevel int) *log.Logger {
if logLevel > l.currentLoggingLevel {
return l.nullLogger
}
switch logLevel {
case noLogging:
return l.nullLogger
case infoLogging:
return l.infoLogger
case debugLogging:
return l.debugLogger
case verboseLogging:
return l.verboseLogger
default:
return l.nullLogger
}
}
//LogLevel returns the current debug level
func (l defaultSDKLogger) LogLevel() int {
return l.currentLoggingLevel
}
func (l defaultSDKLogger) Log(logLevel int, format string, v ...interface{}) error {
logger := l.getLoggerForLevel(logLevel)
logger.Output(4, fmt.Sprintf(format, v...))
return nil
}
//Logln logs v appending a new line at the end
//Deprecated
func Logln(v ...interface{}) {
defaultLogger.Log(infoLogging, "%v\n", v...)
}
// Logf logs v with the provided format
func Logf(format string, v ...interface{}) {
defaultLogger.Log(infoLogging, format, v...)
}
// Debugf logs v with the provided format if debug mode is set
func Debugf(format string, v ...interface{}) {
defaultLogger.Log(debugLogging, format, v...)
}
// Debug logs v if debug mode is set
func Debug(v ...interface{}) {
m := fmt.Sprint(v...)
defaultLogger.Log(debugLogging, "%s", m)
}
// Debugln logs v appending a new line if debug mode is set
func Debugln(v ...interface{}) {
m := fmt.Sprint(v...)
defaultLogger.Log(debugLogging, "%s\n", m)
}
// IfDebug executes closure if debug is enabled
func IfDebug(fn func()) {
if defaultLogger.LogLevel() >= debugLogging {
fn()
}
}

159
vendor/github.com/oracle/oci-go-sdk/common/retry.go generated vendored Normal file
View File

@@ -0,0 +1,159 @@
package common
import (
"context"
"fmt"
"math/rand"
"runtime"
"time"
)
const (
// UnlimitedNumAttemptsValue is the value for indicating unlimited attempts for reaching success
UnlimitedNumAttemptsValue = uint(0)
// number of characters contained in the generated retry token
generatedRetryTokenLength = 32
)
// OCIRetryableRequest represents a request that can be reissued according to the specified policy.
type OCIRetryableRequest interface {
// Any retryable request must implement the OCIRequest interface
OCIRequest
// Each operation specifies default retry behavior. By passing no arguments to this method, the default retry
// behavior, as determined on a per-operation-basis, will be honored. Variadic retry policy option arguments
// passed to this method will override the default behavior.
RetryPolicy() *RetryPolicy
}
// OCIOperationResponse represents the output of an OCIOperation, with additional context of error message
// and operation attempt number.
type OCIOperationResponse struct {
// Response from OCI Operation
Response OCIResponse
// Error from OCI Operation
Error error
// Operation Attempt Number (one-based)
AttemptNumber uint
}
// NewOCIOperationResponse assembles an OCI Operation Response object.
func NewOCIOperationResponse(response OCIResponse, err error, attempt uint) OCIOperationResponse {
return OCIOperationResponse{
Response: response,
Error: err,
AttemptNumber: attempt,
}
}
// RetryPolicy is the class that holds all relevant information for retrying operations.
type RetryPolicy struct {
// MaximumNumberAttempts is the maximum number of times to retry a request. Zero indicates an unlimited
// number of attempts.
MaximumNumberAttempts uint
// ShouldRetryOperation inspects the http response, error, and operation attempt number, and
// - returns true if we should retry the operation
// - returns false otherwise
ShouldRetryOperation func(OCIOperationResponse) bool
// GetNextDuration computes the duration to pause between operation retries.
NextDuration func(OCIOperationResponse) time.Duration
}
// NoRetryPolicy is a helper method that assembles and returns a return policy that indicates an operation should
// never be retried (the operation is performed exactly once).
func NoRetryPolicy() RetryPolicy {
dontRetryOperation := func(OCIOperationResponse) bool { return false }
zeroNextDuration := func(OCIOperationResponse) time.Duration { return 0 * time.Second }
return NewRetryPolicy(uint(1), dontRetryOperation, zeroNextDuration)
}
// NewRetryPolicy is a helper method for assembling a Retry Policy object.
func NewRetryPolicy(attempts uint, retryOperation func(OCIOperationResponse) bool, nextDuration func(OCIOperationResponse) time.Duration) RetryPolicy {
return RetryPolicy{
MaximumNumberAttempts: attempts,
ShouldRetryOperation: retryOperation,
NextDuration: nextDuration,
}
}
// shouldContinueIssuingRequests returns true if we should continue retrying a request, based on the current attempt
// number and the maximum number of attempts specified, or false otherwise.
func shouldContinueIssuingRequests(current, maximum uint) bool {
return maximum == UnlimitedNumAttemptsValue || current <= maximum
}
// RetryToken generates a retry token that must be included on any request passed to the Retry method.
func RetryToken() string {
alphanumericChars := []rune("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
retryToken := make([]rune, generatedRetryTokenLength)
for i := range retryToken {
retryToken[i] = alphanumericChars[rand.Intn(len(alphanumericChars))]
}
return string(retryToken)
}
// Retry is a package-level operation that executes the retryable request using the specified operation and retry policy.
func Retry(ctx context.Context, request OCIRetryableRequest, operation OCIOperation, policy RetryPolicy) (OCIResponse, error) {
type retrierResult struct {
response OCIResponse
err error
}
var response OCIResponse
var err error
retrierChannel := make(chan retrierResult)
go func() {
// Deal with panics more graciously
defer func() {
if r := recover(); r != nil {
stackBuffer := make([]byte, 1024)
bytesWritten := runtime.Stack(stackBuffer, false)
stack := string(stackBuffer[:bytesWritten])
retrierChannel <- retrierResult{nil, fmt.Errorf("panicked while retrying operation. Panic was: %s\nStack: %s", r, stack)}
}
}()
// use a one-based counter because it's easier to think about operation retry in terms of attempt numbering
for currentOperationAttempt := uint(1); shouldContinueIssuingRequests(currentOperationAttempt, policy.MaximumNumberAttempts); currentOperationAttempt++ {
Debugln(fmt.Sprintf("operation attempt #%v", currentOperationAttempt))
response, err = operation(ctx, request)
operationResponse := NewOCIOperationResponse(response, err, currentOperationAttempt)
if !policy.ShouldRetryOperation(operationResponse) {
// we should NOT retry operation based on response and/or error => return
retrierChannel <- retrierResult{response, err}
return
}
duration := policy.NextDuration(operationResponse)
//The following condition is kept for backwards compatibility reasons
if deadline, ok := ctx.Deadline(); ok && time.Now().Add(duration).After(deadline) {
// we want to retry the operation, but the policy is telling us to wait for a duration that exceeds
// the specified overall deadline for the operation => instead of waiting for however long that
// time period is and then aborting, abort now and save the cycles
retrierChannel <- retrierResult{response, DeadlineExceededByBackoff}
return
}
Debugln(fmt.Sprintf("waiting %v before retrying operation", duration))
// sleep before retrying the operation
<-time.After(duration)
}
retrierChannel <- retrierResult{nil, fmt.Errorf("maximum number of attempts exceeded (%v)", policy.MaximumNumberAttempts)}
}()
select {
case <-ctx.Done():
return response, ctx.Err()
case result := <-retrierChannel:
return result.response, result.err
}
}

36
vendor/github.com/oracle/oci-go-sdk/common/version.go generated vendored Normal file
View File

@@ -0,0 +1,36 @@
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
// Code generated by go generate; DO NOT EDIT
package common
import (
"bytes"
"fmt"
"sync"
)
const (
major = "7"
minor = "0"
patch = "0"
tag = ""
)
var once sync.Once
var version string
// Version returns semantic version of the sdk
func Version() string {
once.Do(func() {
ver := fmt.Sprintf("%s.%s.%s", major, minor, patch)
verBuilder := bytes.NewBufferString(ver)
if tag != "" && tag != "-" {
_, err := verBuilder.WriteString(tag)
if err != nil {
verBuilder = bytes.NewBufferString(ver)
}
}
version = verBuilder.String()
})
return version
}

View File

@@ -0,0 +1,80 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// CancelKeyDeletionRequest wrapper for the CancelKeyDeletion operation
type CancelKeyDeletionRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request CancelKeyDeletionRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request CancelKeyDeletionRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request CancelKeyDeletionRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// CancelKeyDeletionResponse wrapper for the CancelKeyDeletion operation
type CancelKeyDeletionResponse struct {
// The underlying http response
RawResponse *http.Response
// The Key instance
Key `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response CancelKeyDeletionResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response CancelKeyDeletionResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,80 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// CancelVaultDeletionRequest wrapper for the CancelVaultDeletion operation
type CancelVaultDeletionRequest struct {
// The OCID of the vault.
VaultId *string `mandatory:"true" contributesTo:"path" name:"vaultId"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request CancelVaultDeletionRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request CancelVaultDeletionRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request CancelVaultDeletionRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// CancelVaultDeletionResponse wrapper for the CancelVaultDeletion operation
type CancelVaultDeletionResponse struct {
// The underlying http response
RawResponse *http.Response
// The Vault instance
Vault `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response CancelVaultDeletionResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response CancelVaultDeletionResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// ChangeKeyCompartmentDetails The representation of ChangeKeyCompartmentDetails
type ChangeKeyCompartmentDetails struct {
// The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment into which the key should be moved.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
}
func (m ChangeKeyCompartmentDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,79 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// ChangeKeyCompartmentRequest wrapper for the ChangeKeyCompartment operation
type ChangeKeyCompartmentRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
ChangeKeyCompartmentDetails `contributesTo:"body"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ChangeKeyCompartmentRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ChangeKeyCompartmentRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ChangeKeyCompartmentRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ChangeKeyCompartmentResponse wrapper for the ChangeKeyCompartment operation
type ChangeKeyCompartmentResponse struct {
// The underlying http response
RawResponse *http.Response
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ChangeKeyCompartmentResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ChangeKeyCompartmentResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// ChangeVaultCompartmentDetails The representation of ChangeVaultCompartmentDetails
type ChangeVaultCompartmentDetails struct {
// The OCID (https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment into which the vault should be moved.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
}
func (m ChangeVaultCompartmentDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,79 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// ChangeVaultCompartmentRequest wrapper for the ChangeVaultCompartment operation
type ChangeVaultCompartmentRequest struct {
// The OCID of the vault.
VaultId *string `mandatory:"true" contributesTo:"path" name:"vaultId"`
ChangeVaultCompartmentDetails `contributesTo:"body"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ChangeVaultCompartmentRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ChangeVaultCompartmentRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ChangeVaultCompartmentRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ChangeVaultCompartmentResponse wrapper for the ChangeVaultCompartment operation
type ChangeVaultCompartmentResponse struct {
// The underlying http response
RawResponse *http.Response
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ChangeVaultCompartmentResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ChangeVaultCompartmentResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,39 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// CreateKeyDetails The representation of CreateKeyDetails
type CreateKeyDetails struct {
// The OCID of the compartment that contains this key.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// A user-friendly name for the key. It does not have to be unique, and it is changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
KeyShape *KeyShape `mandatory:"true" json:"keyShape"`
// Usage of predefined tag keys. These predefined keys are scoped to namespaces.
// Example: `{"foo-namespace": {"bar-key": "foo-value"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// Simple key-value pair that is applied without any predefined name, type, or scope.
// Exists for cross-compatibility only.
// Example: `{"bar-key": "value"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
}
func (m CreateKeyDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,73 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// CreateKeyRequest wrapper for the CreateKey operation
type CreateKeyRequest struct {
// CreateKeyDetails
CreateKeyDetails `contributesTo:"body"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request CreateKeyRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request CreateKeyRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request CreateKeyRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// CreateKeyResponse wrapper for the CreateKey operation
type CreateKeyResponse struct {
// The underlying http response
RawResponse *http.Response
// The Key instance
Key `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response CreateKeyResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response CreateKeyResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,73 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// CreateKeyVersionRequest wrapper for the CreateKeyVersion operation
type CreateKeyVersionRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request CreateKeyVersionRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request CreateKeyVersionRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request CreateKeyVersionRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// CreateKeyVersionResponse wrapper for the CreateKeyVersion operation
type CreateKeyVersionResponse struct {
// The underlying http response
RawResponse *http.Response
// The KeyVersion instance
KeyVersion `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response CreateKeyVersionResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response CreateKeyVersionResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,61 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// CreateVaultDetails The representation of CreateVaultDetails
type CreateVaultDetails struct {
// The OCID of the compartment where you want to create this vault.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// A user-friendly name for the vault. It does not have to be unique, and it is changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The type of vault to create. Each type of vault stores the key with different degrees of isolation and has different options and pricing.
VaultType CreateVaultDetailsVaultTypeEnum `mandatory:"true" json:"vaultType"`
// Usage of predefined tag keys. These predefined keys are scoped to namespaces.
// Example: `{"foo-namespace": {"bar-key": "foo-value"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// Simple key-value pair that is applied without any predefined name, type, or scope.
// Exists for cross-compatibility only.
// Example: `{"bar-key": "value"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
}
func (m CreateVaultDetails) String() string {
return common.PointerString(m)
}
// CreateVaultDetailsVaultTypeEnum Enum with underlying type: string
type CreateVaultDetailsVaultTypeEnum string
// Set of constants representing the allowable values for CreateVaultDetailsVaultTypeEnum
const (
CreateVaultDetailsVaultTypePrivate CreateVaultDetailsVaultTypeEnum = "VIRTUAL_PRIVATE"
)
var mappingCreateVaultDetailsVaultType = map[string]CreateVaultDetailsVaultTypeEnum{
"VIRTUAL_PRIVATE": CreateVaultDetailsVaultTypePrivate,
}
// GetCreateVaultDetailsVaultTypeEnumValues Enumerates the set of values for CreateVaultDetailsVaultTypeEnum
func GetCreateVaultDetailsVaultTypeEnumValues() []CreateVaultDetailsVaultTypeEnum {
values := make([]CreateVaultDetailsVaultTypeEnum, 0)
for _, v := range mappingCreateVaultDetailsVaultType {
values = append(values, v)
}
return values
}

View File

@@ -0,0 +1,73 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// CreateVaultRequest wrapper for the CreateVault operation
type CreateVaultRequest struct {
// CreateVaultDetails
CreateVaultDetails `contributesTo:"body"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request CreateVaultRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request CreateVaultRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request CreateVaultRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// CreateVaultResponse wrapper for the CreateVault operation
type CreateVaultResponse struct {
// The underlying http response
RawResponse *http.Response
// The Vault instance
Vault `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response CreateVaultResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response CreateVaultResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,36 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// DecryptDataDetails The representation of DecryptDataDetails
type DecryptDataDetails struct {
// The encrypted data to decrypt.
Ciphertext *string `mandatory:"true" json:"ciphertext"`
// The OCID of the key used to encrypt the ciphertext.
KeyId *string `mandatory:"true" json:"keyId"`
// Information that can be used to provide an encryption context for the
// encrypted data. The length of the string representation of the associatedData
// must be fewer than 4096 characters.
AssociatedData map[string]string `mandatory:"false" json:"associatedData"`
// Information that can be used to provide context for audit logging. It is a map that contains any addtional
// data the users may have and will be added to the audit logs (if audit logging is enabled)
LoggingContext map[string]string `mandatory:"false" json:"loggingContext"`
}
func (m DecryptDataDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,62 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// DecryptRequest wrapper for the Decrypt operation
type DecryptRequest struct {
// DecryptDataDetails
DecryptDataDetails `contributesTo:"body"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request DecryptRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request DecryptRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request DecryptRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// DecryptResponse wrapper for the Decrypt operation
type DecryptResponse struct {
// The underlying http response
RawResponse *http.Response
// The DecryptedData instance
DecryptedData `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response DecryptResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response DecryptResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,27 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// DecryptedData The representation of DecryptedData
type DecryptedData struct {
// The decrypted data, expressed as a base64-encoded value.
Plaintext *string `mandatory:"true" json:"plaintext"`
// Checksum of the decrypted data.
PlaintextChecksum *string `mandatory:"true" json:"plaintextChecksum"`
}
func (m DecryptedData) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,80 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// DisableKeyRequest wrapper for the DisableKey operation
type DisableKeyRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request DisableKeyRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request DisableKeyRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request DisableKeyRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// DisableKeyResponse wrapper for the DisableKey operation
type DisableKeyResponse struct {
// The underlying http response
RawResponse *http.Response
// The Key instance
Key `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response DisableKeyResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response DisableKeyResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,80 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// EnableKeyRequest wrapper for the EnableKey operation
type EnableKeyRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request EnableKeyRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request EnableKeyRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request EnableKeyRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// EnableKeyResponse wrapper for the EnableKey operation
type EnableKeyResponse struct {
// The underlying http response
RawResponse *http.Response
// The Key instance
Key `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response EnableKeyResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response EnableKeyResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,36 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// EncryptDataDetails The representation of EncryptDataDetails
type EncryptDataDetails struct {
// The OCID of the key to encrypt with.
KeyId *string `mandatory:"true" json:"keyId"`
// The plaintext data to encrypt.
Plaintext *string `mandatory:"true" json:"plaintext"`
// Information that can be used to provide an encryption context for the
// encrypted data. The length of the string representation of the associatedData
// must be fewer than 4096 characters.
AssociatedData map[string]string `mandatory:"false" json:"associatedData"`
// Information that can be used to provide context for audit logging. It is a map that contains any addtional
// data the users may have and will be added to the audit logs (if audit logging is enabled)
LoggingContext map[string]string `mandatory:"false" json:"loggingContext"`
}
func (m EncryptDataDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,62 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// EncryptRequest wrapper for the Encrypt operation
type EncryptRequest struct {
// EncryptDataDetails
EncryptDataDetails `contributesTo:"body"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request EncryptRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request EncryptRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request EncryptRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// EncryptResponse wrapper for the Encrypt operation
type EncryptResponse struct {
// The underlying http response
RawResponse *http.Response
// The EncryptedData instance
EncryptedData `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response EncryptResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response EncryptResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,24 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// EncryptedData The representation of EncryptedData
type EncryptedData struct {
// The encrypted data.
Ciphertext *string `mandatory:"true" json:"ciphertext"`
}
func (m EncryptedData) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,62 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// GenerateDataEncryptionKeyRequest wrapper for the GenerateDataEncryptionKey operation
type GenerateDataEncryptionKeyRequest struct {
// GenerateKeyDetails
GenerateKeyDetails `contributesTo:"body"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request GenerateDataEncryptionKeyRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request GenerateDataEncryptionKeyRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request GenerateDataEncryptionKeyRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// GenerateDataEncryptionKeyResponse wrapper for the GenerateDataEncryptionKey operation
type GenerateDataEncryptionKeyResponse struct {
// The underlying http response
RawResponse *http.Response
// The GeneratedKey instance
GeneratedKey `presentIn:"body"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response GenerateDataEncryptionKeyResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response GenerateDataEncryptionKeyResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,38 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// GenerateKeyDetails The representation of GenerateKeyDetails
type GenerateKeyDetails struct {
// If true, the generated key is also returned unencrypted.
IncludePlaintextKey *bool `mandatory:"true" json:"includePlaintextKey"`
// The OCID of the master encryption key to encrypt the generated data encryption key with.
KeyId *string `mandatory:"true" json:"keyId"`
KeyShape *KeyShape `mandatory:"true" json:"keyShape"`
// Information that can be used to provide an encryption context for the
// encrypted data. The length of the string representation of the associatedData
// must be fewer than 4096 characters.
AssociatedData map[string]string `mandatory:"false" json:"associatedData"`
// Information that can be used to provide context for audit logging. It is a map that contains any addtional
// data the users may have and will be added to the audit logs (if audit logging is enabled)
LoggingContext map[string]string `mandatory:"false" json:"loggingContext"`
}
func (m GenerateKeyDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,35 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// GeneratedKey The representation of GeneratedKey
type GeneratedKey struct {
// The encrypted generated data encryption key.
Ciphertext *string `mandatory:"true" json:"ciphertext"`
// The plaintext generated data encryption key, a base64-encoded
// sequence of random bytes, which is included if the
// GenerateDataEncryptionKey request includes the "includePlaintextKey"
// parameter and sets its value to 'true'.
Plaintext *string `mandatory:"false" json:"plaintext"`
// The checksum of the plaintext generated data encryption key, which
// is included if the GenerateDataEncryptionKey request includes the
// "includePlaintextKey parameter and sets its value to 'true'.
PlaintextChecksum *string `mandatory:"false" json:"plaintextChecksum"`
}
func (m GeneratedKey) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,65 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// GetKeyRequest wrapper for the GetKey operation
type GetKeyRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request GetKeyRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request GetKeyRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request GetKeyRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// GetKeyResponse wrapper for the GetKey operation
type GetKeyResponse struct {
// The underlying http response
RawResponse *http.Response
// The Key instance
Key `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response GetKeyResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response GetKeyResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,68 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// GetKeyVersionRequest wrapper for the GetKeyVersion operation
type GetKeyVersionRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// The OCID of the key version.
KeyVersionId *string `mandatory:"true" contributesTo:"path" name:"keyVersionId"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request GetKeyVersionRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request GetKeyVersionRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request GetKeyVersionRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// GetKeyVersionResponse wrapper for the GetKeyVersion operation
type GetKeyVersionResponse struct {
// The underlying http response
RawResponse *http.Response
// The KeyVersion instance
KeyVersion `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response GetKeyVersionResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response GetKeyVersionResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,65 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// GetVaultRequest wrapper for the GetVault operation
type GetVaultRequest struct {
// The OCID of the vault.
VaultId *string `mandatory:"true" contributesTo:"path" name:"vaultId"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request GetVaultRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request GetVaultRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request GetVaultRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// GetVaultResponse wrapper for the GetVault operation
type GetVaultResponse struct {
// The underlying http response
RawResponse *http.Response
// The Vault instance
Vault `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response GetVaultResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response GetVaultResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,103 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// Key The representation of Key
type Key struct {
// The OCID of the compartment that contains this key.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// The OCID of the KeyVersion resource used in cryptographic operations. During key rotation, service might be in a transitional state
// where this or a newer KeyVersion are used intermittently. The currentKeyVersion field is updated when the service is guaranteed to
// use the new KeyVersion for all subsequent encryption operations.
CurrentKeyVersion *string `mandatory:"true" json:"currentKeyVersion"`
// A user-friendly name for the key. It does not have to be unique, and it is changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The OCID of the key.
Id *string `mandatory:"true" json:"id"`
KeyShape *KeyShape `mandatory:"true" json:"keyShape"`
// The key's current state.
// Example: `ENABLED`
LifecycleState KeyLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`
// The date and time the key was created, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format.
// Example: `2018-04-03T21:10:29.600Z`
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// The OCID of the vault that contains this key.
VaultId *string `mandatory:"true" json:"vaultId"`
// Usage of predefined tag keys. These predefined keys are scoped to namespaces.
// Example: `{"foo-namespace": {"bar-key": "foo-value"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// Simple key-value pair that is applied without any predefined name, type, or scope.
// Exists for cross-compatibility only.
// Example: `{"bar-key": "value"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
// An optional property for the deletion time of the key, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format.
// Example: `2019-04-03T21:10:29.600Z`
TimeOfDeletion *common.SDKTime `mandatory:"false" json:"timeOfDeletion"`
}
func (m Key) String() string {
return common.PointerString(m)
}
// KeyLifecycleStateEnum Enum with underlying type: string
type KeyLifecycleStateEnum string
// Set of constants representing the allowable values for KeyLifecycleStateEnum
const (
KeyLifecycleStateCreating KeyLifecycleStateEnum = "CREATING"
KeyLifecycleStateEnabling KeyLifecycleStateEnum = "ENABLING"
KeyLifecycleStateEnabled KeyLifecycleStateEnum = "ENABLED"
KeyLifecycleStateDisabling KeyLifecycleStateEnum = "DISABLING"
KeyLifecycleStateDisabled KeyLifecycleStateEnum = "DISABLED"
KeyLifecycleStateDeleting KeyLifecycleStateEnum = "DELETING"
KeyLifecycleStateDeleted KeyLifecycleStateEnum = "DELETED"
KeyLifecycleStatePendingDeletion KeyLifecycleStateEnum = "PENDING_DELETION"
KeyLifecycleStateSchedulingDeletion KeyLifecycleStateEnum = "SCHEDULING_DELETION"
KeyLifecycleStateCancellingDeletion KeyLifecycleStateEnum = "CANCELLING_DELETION"
KeyLifecycleStateUpdating KeyLifecycleStateEnum = "UPDATING"
)
var mappingKeyLifecycleState = map[string]KeyLifecycleStateEnum{
"CREATING": KeyLifecycleStateCreating,
"ENABLING": KeyLifecycleStateEnabling,
"ENABLED": KeyLifecycleStateEnabled,
"DISABLING": KeyLifecycleStateDisabling,
"DISABLED": KeyLifecycleStateDisabled,
"DELETING": KeyLifecycleStateDeleting,
"DELETED": KeyLifecycleStateDeleted,
"PENDING_DELETION": KeyLifecycleStatePendingDeletion,
"SCHEDULING_DELETION": KeyLifecycleStateSchedulingDeletion,
"CANCELLING_DELETION": KeyLifecycleStateCancellingDeletion,
"UPDATING": KeyLifecycleStateUpdating,
}
// GetKeyLifecycleStateEnumValues Enumerates the set of values for KeyLifecycleStateEnum
func GetKeyLifecycleStateEnumValues() []KeyLifecycleStateEnum {
values := make([]KeyLifecycleStateEnum, 0)
for _, v := range mappingKeyLifecycleState {
values = append(values, v)
}
return values
}

View File

@@ -0,0 +1,48 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// KeyShape The cryptographic properties of a key.
type KeyShape struct {
// The algorithm used by a key's KeyVersions to encrypt or decrypt.
Algorithm KeyShapeAlgorithmEnum `mandatory:"true" json:"algorithm"`
// The length of the key, expressed as an integer. Values of 16, 24, or 32 are supported.
Length *int `mandatory:"true" json:"length"`
}
func (m KeyShape) String() string {
return common.PointerString(m)
}
// KeyShapeAlgorithmEnum Enum with underlying type: string
type KeyShapeAlgorithmEnum string
// Set of constants representing the allowable values for KeyShapeAlgorithmEnum
const (
KeyShapeAlgorithmAes KeyShapeAlgorithmEnum = "AES"
)
var mappingKeyShapeAlgorithm = map[string]KeyShapeAlgorithmEnum{
"AES": KeyShapeAlgorithmAes,
}
// GetKeyShapeAlgorithmEnumValues Enumerates the set of values for KeyShapeAlgorithmEnum
func GetKeyShapeAlgorithmEnumValues() []KeyShapeAlgorithmEnum {
values := make([]KeyShapeAlgorithmEnum, 0)
for _, v := range mappingKeyShapeAlgorithm {
values = append(values, v)
}
return values
}

View File

@@ -0,0 +1,92 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// KeySummary The representation of KeySummary
type KeySummary struct {
// The OCID of the compartment that contains the key.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// A user-friendly name for the key. It does not have to be unique, and it is changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The OCID of the key.
Id *string `mandatory:"true" json:"id"`
// The key's current state.
// Example: `ENABLED`
LifecycleState KeySummaryLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`
// The date and time the key was created, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format.
// Example: `2018-04-03T21:10:29.600Z`
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// The OCID of the vault that contains the key.
VaultId *string `mandatory:"true" json:"vaultId"`
// Usage of predefined tag keys. These predefined keys are scoped to namespaces.
// Example: `{"foo-namespace": {"bar-key": "foo-value"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// Simple key-value pair that is applied without any predefined name, type, or scope.
// Exists for cross-compatibility only.
// Example: `{"bar-key": "value"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
}
func (m KeySummary) String() string {
return common.PointerString(m)
}
// KeySummaryLifecycleStateEnum Enum with underlying type: string
type KeySummaryLifecycleStateEnum string
// Set of constants representing the allowable values for KeySummaryLifecycleStateEnum
const (
KeySummaryLifecycleStateCreating KeySummaryLifecycleStateEnum = "CREATING"
KeySummaryLifecycleStateEnabling KeySummaryLifecycleStateEnum = "ENABLING"
KeySummaryLifecycleStateEnabled KeySummaryLifecycleStateEnum = "ENABLED"
KeySummaryLifecycleStateDisabling KeySummaryLifecycleStateEnum = "DISABLING"
KeySummaryLifecycleStateDisabled KeySummaryLifecycleStateEnum = "DISABLED"
KeySummaryLifecycleStateDeleting KeySummaryLifecycleStateEnum = "DELETING"
KeySummaryLifecycleStateDeleted KeySummaryLifecycleStateEnum = "DELETED"
KeySummaryLifecycleStatePendingDeletion KeySummaryLifecycleStateEnum = "PENDING_DELETION"
KeySummaryLifecycleStateSchedulingDeletion KeySummaryLifecycleStateEnum = "SCHEDULING_DELETION"
KeySummaryLifecycleStateCancellingDeletion KeySummaryLifecycleStateEnum = "CANCELLING_DELETION"
KeySummaryLifecycleStateUpdating KeySummaryLifecycleStateEnum = "UPDATING"
)
var mappingKeySummaryLifecycleState = map[string]KeySummaryLifecycleStateEnum{
"CREATING": KeySummaryLifecycleStateCreating,
"ENABLING": KeySummaryLifecycleStateEnabling,
"ENABLED": KeySummaryLifecycleStateEnabled,
"DISABLING": KeySummaryLifecycleStateDisabling,
"DISABLED": KeySummaryLifecycleStateDisabled,
"DELETING": KeySummaryLifecycleStateDeleting,
"DELETED": KeySummaryLifecycleStateDeleted,
"PENDING_DELETION": KeySummaryLifecycleStatePendingDeletion,
"SCHEDULING_DELETION": KeySummaryLifecycleStateSchedulingDeletion,
"CANCELLING_DELETION": KeySummaryLifecycleStateCancellingDeletion,
"UPDATING": KeySummaryLifecycleStateUpdating,
}
// GetKeySummaryLifecycleStateEnumValues Enumerates the set of values for KeySummaryLifecycleStateEnum
func GetKeySummaryLifecycleStateEnumValues() []KeySummaryLifecycleStateEnum {
values := make([]KeySummaryLifecycleStateEnum, 0)
for _, v := range mappingKeySummaryLifecycleState {
values = append(values, v)
}
return values
}

View File

@@ -0,0 +1,37 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// KeyVersion The representation of KeyVersion
type KeyVersion struct {
// The OCID of the compartment that contains this key version.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// The OCID of the key version.
Id *string `mandatory:"true" json:"id"`
// The OCID of the key associated with this key version.
KeyId *string `mandatory:"true" json:"keyId"`
// The date and time this key version was created, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format.
// Example: "2018-04-03T21:10:29.600Z"
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// The OCID of the vault that contains this key version.
VaultId *string `mandatory:"true" json:"vaultId"`
}
func (m KeyVersion) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,37 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// KeyVersionSummary The representation of KeyVersionSummary
type KeyVersionSummary struct {
// The OCID of the compartment that contains this key version.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// The OCID of the key version.
Id *string `mandatory:"true" json:"id"`
// The OCID of the key associated with this key version.
KeyId *string `mandatory:"true" json:"keyId"`
// The date and time this key version was created, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format.
// Example: `2018-04-03T21:10:29.600Z`
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// The OCID of the vault that contains this key version.
VaultId *string `mandatory:"true" json:"vaultId"`
}
func (m KeyVersionSummary) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,180 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"context"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
//KmsCryptoClient a client for KmsCrypto
type KmsCryptoClient struct {
common.BaseClient
config *common.ConfigurationProvider
}
// NewKmsCryptoClientWithConfigurationProvider Creates a new default KmsCrypto client with the given configuration provider.
// the configuration provider will be used for the default signer
func NewKmsCryptoClientWithConfigurationProvider(configProvider common.ConfigurationProvider, endpoint string) (client KmsCryptoClient, err error) {
baseClient, err := common.NewClientWithConfig(configProvider)
if err != nil {
return
}
client = KmsCryptoClient{BaseClient: baseClient}
client.BasePath = ""
client.Host = endpoint
err = client.setConfigurationProvider(configProvider)
return
}
// SetConfigurationProvider sets the configuration provider including the region, returns an error if is not valid
func (client *KmsCryptoClient) setConfigurationProvider(configProvider common.ConfigurationProvider) error {
if ok, err := common.IsConfigurationProviderValid(configProvider); !ok {
return err
}
client.config = &configProvider
return nil
}
// ConfigurationProvider the ConfigurationProvider used in this client, or null if none set
func (client *KmsCryptoClient) ConfigurationProvider() *common.ConfigurationProvider {
return client.config
}
// Decrypt Decrypts data using the given DecryptDataDetails resource.
func (client KmsCryptoClient) Decrypt(ctx context.Context, request DecryptRequest) (response DecryptResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.decrypt, policy)
if err != nil {
if ociResponse != nil {
response = DecryptResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(DecryptResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into DecryptResponse")
}
return
}
// decrypt implements the OCIOperation interface (enables retrying operations)
func (client KmsCryptoClient) decrypt(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/decrypt")
if err != nil {
return nil, err
}
var response DecryptResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// Encrypt Encrypts data using the given EncryptDataDetails resource.
// Plaintext included in the example request is a base64-encoded value
// of a UTF-8 string.
func (client KmsCryptoClient) Encrypt(ctx context.Context, request EncryptRequest) (response EncryptResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.encrypt, policy)
if err != nil {
if ociResponse != nil {
response = EncryptResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(EncryptResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into EncryptResponse")
}
return
}
// encrypt implements the OCIOperation interface (enables retrying operations)
func (client KmsCryptoClient) encrypt(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/encrypt")
if err != nil {
return nil, err
}
var response EncryptResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// GenerateDataEncryptionKey Generates a key that you can use to encrypt or decrypt data.
func (client KmsCryptoClient) GenerateDataEncryptionKey(ctx context.Context, request GenerateDataEncryptionKeyRequest) (response GenerateDataEncryptionKeyResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.generateDataEncryptionKey, policy)
if err != nil {
if ociResponse != nil {
response = GenerateDataEncryptionKeyResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(GenerateDataEncryptionKeyResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into GenerateDataEncryptionKeyResponse")
}
return
}
// generateDataEncryptionKey implements the OCIOperation interface (enables retrying operations)
func (client KmsCryptoClient) generateDataEncryptionKey(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/generateDataEncryptionKey")
if err != nil {
return nil, err
}
var response GenerateDataEncryptionKeyResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}

View File

@@ -0,0 +1,599 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"context"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
//KmsManagementClient a client for KmsManagement
type KmsManagementClient struct {
common.BaseClient
config *common.ConfigurationProvider
}
// NewKmsManagementClientWithConfigurationProvider Creates a new default KmsManagement client with the given configuration provider.
// the configuration provider will be used for the default signer
func NewKmsManagementClientWithConfigurationProvider(configProvider common.ConfigurationProvider, endpoint string) (client KmsManagementClient, err error) {
baseClient, err := common.NewClientWithConfig(configProvider)
if err != nil {
return
}
client = KmsManagementClient{BaseClient: baseClient}
client.BasePath = ""
client.Host = endpoint
err = client.setConfigurationProvider(configProvider)
return
}
// SetConfigurationProvider sets the configuration provider including the region, returns an error if is not valid
func (client *KmsManagementClient) setConfigurationProvider(configProvider common.ConfigurationProvider) error {
if ok, err := common.IsConfigurationProviderValid(configProvider); !ok {
return err
}
client.config = &configProvider
return nil
}
// ConfigurationProvider the ConfigurationProvider used in this client, or null if none set
func (client *KmsManagementClient) ConfigurationProvider() *common.ConfigurationProvider {
return client.config
}
// CancelKeyDeletion Cancels the scheduled deletion of the specified key. Canceling
// a scheduled deletion restores the key to the respective
// states they were in before the deletion was scheduled.
func (client KmsManagementClient) CancelKeyDeletion(ctx context.Context, request CancelKeyDeletionRequest) (response CancelKeyDeletionResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.cancelKeyDeletion, policy)
if err != nil {
if ociResponse != nil {
response = CancelKeyDeletionResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(CancelKeyDeletionResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into CancelKeyDeletionResponse")
}
return
}
// cancelKeyDeletion implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) cancelKeyDeletion(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/keys/{keyId}/actions/cancelDeletion")
if err != nil {
return nil, err
}
var response CancelKeyDeletionResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// ChangeKeyCompartment Moves a key into a different compartment. When provided, If-Match is checked against ETag values of the key.
func (client KmsManagementClient) ChangeKeyCompartment(ctx context.Context, request ChangeKeyCompartmentRequest) (response ChangeKeyCompartmentResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.changeKeyCompartment, policy)
if err != nil {
if ociResponse != nil {
response = ChangeKeyCompartmentResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(ChangeKeyCompartmentResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into ChangeKeyCompartmentResponse")
}
return
}
// changeKeyCompartment implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) changeKeyCompartment(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/keys/{keyId}/actions/changeCompartment")
if err != nil {
return nil, err
}
var response ChangeKeyCompartmentResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// CreateKey Creates a new key.
func (client KmsManagementClient) CreateKey(ctx context.Context, request CreateKeyRequest) (response CreateKeyResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.createKey, policy)
if err != nil {
if ociResponse != nil {
response = CreateKeyResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(CreateKeyResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into CreateKeyResponse")
}
return
}
// createKey implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) createKey(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/keys")
if err != nil {
return nil, err
}
var response CreateKeyResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// CreateKeyVersion Generates new cryptographic material for a key. The key must be in an `ENABLED` state to be
// rotated.
func (client KmsManagementClient) CreateKeyVersion(ctx context.Context, request CreateKeyVersionRequest) (response CreateKeyVersionResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.createKeyVersion, policy)
if err != nil {
if ociResponse != nil {
response = CreateKeyVersionResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(CreateKeyVersionResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into CreateKeyVersionResponse")
}
return
}
// createKeyVersion implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) createKeyVersion(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/keys/{keyId}/keyVersions")
if err != nil {
return nil, err
}
var response CreateKeyVersionResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// DisableKey Disables a key to make it unavailable for encryption
// or decryption.
func (client KmsManagementClient) DisableKey(ctx context.Context, request DisableKeyRequest) (response DisableKeyResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.disableKey, policy)
if err != nil {
if ociResponse != nil {
response = DisableKeyResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(DisableKeyResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into DisableKeyResponse")
}
return
}
// disableKey implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) disableKey(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/keys/{keyId}/actions/disable")
if err != nil {
return nil, err
}
var response DisableKeyResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// EnableKey Enables a key to make it available for encryption or
// decryption.
func (client KmsManagementClient) EnableKey(ctx context.Context, request EnableKeyRequest) (response EnableKeyResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.enableKey, policy)
if err != nil {
if ociResponse != nil {
response = EnableKeyResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(EnableKeyResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into EnableKeyResponse")
}
return
}
// enableKey implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) enableKey(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/keys/{keyId}/actions/enable")
if err != nil {
return nil, err
}
var response EnableKeyResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// GetKey Gets information about the specified key.
func (client KmsManagementClient) GetKey(ctx context.Context, request GetKeyRequest) (response GetKeyResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.getKey, policy)
if err != nil {
if ociResponse != nil {
response = GetKeyResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(GetKeyResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into GetKeyResponse")
}
return
}
// getKey implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) getKey(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodGet, "/20180608/keys/{keyId}")
if err != nil {
return nil, err
}
var response GetKeyResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// GetKeyVersion Gets information about the specified key version.
func (client KmsManagementClient) GetKeyVersion(ctx context.Context, request GetKeyVersionRequest) (response GetKeyVersionResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.getKeyVersion, policy)
if err != nil {
if ociResponse != nil {
response = GetKeyVersionResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(GetKeyVersionResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into GetKeyVersionResponse")
}
return
}
// getKeyVersion implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) getKeyVersion(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodGet, "/20180608/keys/{keyId}/keyVersions/{keyVersionId}")
if err != nil {
return nil, err
}
var response GetKeyVersionResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// ListKeyVersions Lists all key versions for the specified key.
func (client KmsManagementClient) ListKeyVersions(ctx context.Context, request ListKeyVersionsRequest) (response ListKeyVersionsResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.listKeyVersions, policy)
if err != nil {
if ociResponse != nil {
response = ListKeyVersionsResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(ListKeyVersionsResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into ListKeyVersionsResponse")
}
return
}
// listKeyVersions implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) listKeyVersions(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodGet, "/20180608/keys/{keyId}/keyVersions")
if err != nil {
return nil, err
}
var response ListKeyVersionsResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// ListKeys Lists the keys in the specified vault and compartment.
func (client KmsManagementClient) ListKeys(ctx context.Context, request ListKeysRequest) (response ListKeysResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.listKeys, policy)
if err != nil {
if ociResponse != nil {
response = ListKeysResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(ListKeysResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into ListKeysResponse")
}
return
}
// listKeys implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) listKeys(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodGet, "/20180608/keys")
if err != nil {
return nil, err
}
var response ListKeysResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// ScheduleKeyDeletion Schedules the deletion of the specified key. This sets the state of the key
// to `PENDING_DELETION` and then deletes it after the retention period ends.
func (client KmsManagementClient) ScheduleKeyDeletion(ctx context.Context, request ScheduleKeyDeletionRequest) (response ScheduleKeyDeletionResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.scheduleKeyDeletion, policy)
if err != nil {
if ociResponse != nil {
response = ScheduleKeyDeletionResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(ScheduleKeyDeletionResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into ScheduleKeyDeletionResponse")
}
return
}
// scheduleKeyDeletion implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) scheduleKeyDeletion(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/keys/{keyId}/actions/scheduleDeletion")
if err != nil {
return nil, err
}
var response ScheduleKeyDeletionResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// UpdateKey Updates the properties of a key. Specifically, you can update the
// `displayName`, `freeformTags`, and `definedTags` properties. Furthermore,
// the key must in an `ACTIVE` or `CREATING` state to be updated.
func (client KmsManagementClient) UpdateKey(ctx context.Context, request UpdateKeyRequest) (response UpdateKeyResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.updateKey, policy)
if err != nil {
if ociResponse != nil {
response = UpdateKeyResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(UpdateKeyResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into UpdateKeyResponse")
}
return
}
// updateKey implements the OCIOperation interface (enables retrying operations)
func (client KmsManagementClient) updateKey(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPut, "/20180608/keys/{keyId}")
if err != nil {
return nil, err
}
var response UpdateKeyResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}

View File

@@ -0,0 +1,386 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"context"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
//KmsVaultClient a client for KmsVault
type KmsVaultClient struct {
common.BaseClient
config *common.ConfigurationProvider
}
// NewKmsVaultClientWithConfigurationProvider Creates a new default KmsVault client with the given configuration provider.
// the configuration provider will be used for the default signer as well as reading the region
func NewKmsVaultClientWithConfigurationProvider(configProvider common.ConfigurationProvider) (client KmsVaultClient, err error) {
baseClient, err := common.NewClientWithConfig(configProvider)
if err != nil {
return
}
client = KmsVaultClient{BaseClient: baseClient}
client.BasePath = ""
err = client.setConfigurationProvider(configProvider)
return
}
// SetRegion overrides the region of this client.
func (client *KmsVaultClient) SetRegion(region string) {
client.Host = common.StringToRegion(region).Endpoint("kms")
}
// SetConfigurationProvider sets the configuration provider including the region, returns an error if is not valid
func (client *KmsVaultClient) setConfigurationProvider(configProvider common.ConfigurationProvider) error {
if ok, err := common.IsConfigurationProviderValid(configProvider); !ok {
return err
}
// Error has been checked already
region, _ := configProvider.Region()
client.SetRegion(region)
client.config = &configProvider
return nil
}
// ConfigurationProvider the ConfigurationProvider used in this client, or null if none set
func (client *KmsVaultClient) ConfigurationProvider() *common.ConfigurationProvider {
return client.config
}
// CancelVaultDeletion Cancels the scheduled deletion of the specified vault. Canceling a scheduled deletion
// restores the vault and all keys in it to the respective states they were in before
// the deletion was scheduled. All the keys that have already been scheduled deletion before the
// scheduled deletion of the vault will also remain in their state and timeOfDeletion.
func (client KmsVaultClient) CancelVaultDeletion(ctx context.Context, request CancelVaultDeletionRequest) (response CancelVaultDeletionResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.cancelVaultDeletion, policy)
if err != nil {
if ociResponse != nil {
response = CancelVaultDeletionResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(CancelVaultDeletionResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into CancelVaultDeletionResponse")
}
return
}
// cancelVaultDeletion implements the OCIOperation interface (enables retrying operations)
func (client KmsVaultClient) cancelVaultDeletion(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/vaults/{vaultId}/actions/cancelDeletion")
if err != nil {
return nil, err
}
var response CancelVaultDeletionResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// ChangeVaultCompartment Moves a vault into a different compartment. When provided, If-Match is checked against ETag values of the resource.
func (client KmsVaultClient) ChangeVaultCompartment(ctx context.Context, request ChangeVaultCompartmentRequest) (response ChangeVaultCompartmentResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.changeVaultCompartment, policy)
if err != nil {
if ociResponse != nil {
response = ChangeVaultCompartmentResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(ChangeVaultCompartmentResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into ChangeVaultCompartmentResponse")
}
return
}
// changeVaultCompartment implements the OCIOperation interface (enables retrying operations)
func (client KmsVaultClient) changeVaultCompartment(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/vaults/{vaultId}/actions/changeCompartment")
if err != nil {
return nil, err
}
var response ChangeVaultCompartmentResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// CreateVault Creates a new vault. The type of vault you create determines key
// placement, pricing, and available options. Options include storage
// isolation, a dedicated service endpoint instead of a shared service
// endpoint for API calls, and a dedicated hardware security module (HSM) or a multitenant HSM.
func (client KmsVaultClient) CreateVault(ctx context.Context, request CreateVaultRequest) (response CreateVaultResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.createVault, policy)
if err != nil {
if ociResponse != nil {
response = CreateVaultResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(CreateVaultResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into CreateVaultResponse")
}
return
}
// createVault implements the OCIOperation interface (enables retrying operations)
func (client KmsVaultClient) createVault(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/vaults")
if err != nil {
return nil, err
}
var response CreateVaultResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// GetVault Gets the specified vault's configuration information.
func (client KmsVaultClient) GetVault(ctx context.Context, request GetVaultRequest) (response GetVaultResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.getVault, policy)
if err != nil {
if ociResponse != nil {
response = GetVaultResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(GetVaultResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into GetVaultResponse")
}
return
}
// getVault implements the OCIOperation interface (enables retrying operations)
func (client KmsVaultClient) getVault(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodGet, "/20180608/vaults/{vaultId}")
if err != nil {
return nil, err
}
var response GetVaultResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// ListVaults Lists the vaults in the specified compartment.
func (client KmsVaultClient) ListVaults(ctx context.Context, request ListVaultsRequest) (response ListVaultsResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.listVaults, policy)
if err != nil {
if ociResponse != nil {
response = ListVaultsResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(ListVaultsResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into ListVaultsResponse")
}
return
}
// listVaults implements the OCIOperation interface (enables retrying operations)
func (client KmsVaultClient) listVaults(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodGet, "/20180608/vaults")
if err != nil {
return nil, err
}
var response ListVaultsResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// ScheduleVaultDeletion Schedules the deletion of the specified vault. This sets the state of the vault and
// keys that are not scheduled deletion in it to `PENDING_DELETION` and then deletes them
// after the retention period ends.
// The state and the timeOfDeletion of the keys that have already been scheduled for deletion
// will not change. If any keys in it are scheduled for deletion after the specified timeOfDeletion
// for the vault, the call will be rejected with status code 409.
func (client KmsVaultClient) ScheduleVaultDeletion(ctx context.Context, request ScheduleVaultDeletionRequest) (response ScheduleVaultDeletionResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
if !(request.OpcRetryToken != nil && *request.OpcRetryToken != "") {
request.OpcRetryToken = common.String(common.RetryToken())
}
ociResponse, err = common.Retry(ctx, request, client.scheduleVaultDeletion, policy)
if err != nil {
if ociResponse != nil {
response = ScheduleVaultDeletionResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(ScheduleVaultDeletionResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into ScheduleVaultDeletionResponse")
}
return
}
// scheduleVaultDeletion implements the OCIOperation interface (enables retrying operations)
func (client KmsVaultClient) scheduleVaultDeletion(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPost, "/20180608/vaults/{vaultId}/actions/scheduleDeletion")
if err != nil {
return nil, err
}
var response ScheduleVaultDeletionResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}
// UpdateVault Updates the properties of a vault. Specifically, you can update the
// `displayName`, `freeformTags`, and `definedTags` properties. Furthermore,
// the vault must be in an `ACTIVE` or `CREATING` state to be updated.
func (client KmsVaultClient) UpdateVault(ctx context.Context, request UpdateVaultRequest) (response UpdateVaultResponse, err error) {
var ociResponse common.OCIResponse
policy := common.NoRetryPolicy()
if request.RetryPolicy() != nil {
policy = *request.RetryPolicy()
}
ociResponse, err = common.Retry(ctx, request, client.updateVault, policy)
if err != nil {
if ociResponse != nil {
response = UpdateVaultResponse{RawResponse: ociResponse.HTTPResponse()}
}
return
}
if convertedResponse, ok := ociResponse.(UpdateVaultResponse); ok {
response = convertedResponse
} else {
err = fmt.Errorf("failed to convert OCIResponse into UpdateVaultResponse")
}
return
}
// updateVault implements the OCIOperation interface (enables retrying operations)
func (client KmsVaultClient) updateVault(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {
httpRequest, err := request.HTTPRequest(http.MethodPut, "/20180608/vaults/{vaultId}")
if err != nil {
return nil, err
}
var response UpdateVaultResponse
var httpResponse *http.Response
httpResponse, err = client.Call(ctx, &httpRequest)
defer common.CloseBodyIfValid(httpResponse)
response.RawResponse = httpResponse
if err != nil {
return response, err
}
err = common.UnmarshalResponse(httpResponse, &response)
return response, err
}

View File

@@ -0,0 +1,129 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// ListKeyVersionsRequest wrapper for the ListKeyVersions operation
type ListKeyVersionsRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// The maximum number of items to return in a paginated "List" call.
Limit *int `mandatory:"false" contributesTo:"query" name:"limit"`
// The value of the `opc-next-page` response header
// from the previous "List" call.
Page *string `mandatory:"false" contributesTo:"query" name:"page"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// The field to sort by. You can specify only one sort order. The default
// order for TIMECREATED is descending. The default order for DISPLAYNAME
// is ascending.
SortBy ListKeyVersionsSortByEnum `mandatory:"false" contributesTo:"query" name:"sortBy" omitEmpty:"true"`
// The sort order to use, either ascending (`ASC`) or descending (`DESC`).
SortOrder ListKeyVersionsSortOrderEnum `mandatory:"false" contributesTo:"query" name:"sortOrder" omitEmpty:"true"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ListKeyVersionsRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ListKeyVersionsRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ListKeyVersionsRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ListKeyVersionsResponse wrapper for the ListKeyVersions operation
type ListKeyVersionsResponse struct {
// The underlying http response
RawResponse *http.Response
// A list of []KeyVersionSummary instances
Items []KeyVersionSummary `presentIn:"body"`
// For pagination of a list of items. When paging through a list, if this header appears in the response,
// then there are additional items still to get. Include this value as the `page` parameter for the
// subsequent GET request. For information about pagination, see
// List Pagination (https://docs.cloud.oracle.com/Content/API/Concepts/usingapi.htm#List_Pagination).
OpcNextPage *string `presentIn:"header" name:"opc-next-page"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ListKeyVersionsResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ListKeyVersionsResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
// ListKeyVersionsSortByEnum Enum with underlying type: string
type ListKeyVersionsSortByEnum string
// Set of constants representing the allowable values for ListKeyVersionsSortByEnum
const (
ListKeyVersionsSortByTimecreated ListKeyVersionsSortByEnum = "TIMECREATED"
ListKeyVersionsSortByDisplayname ListKeyVersionsSortByEnum = "DISPLAYNAME"
)
var mappingListKeyVersionsSortBy = map[string]ListKeyVersionsSortByEnum{
"TIMECREATED": ListKeyVersionsSortByTimecreated,
"DISPLAYNAME": ListKeyVersionsSortByDisplayname,
}
// GetListKeyVersionsSortByEnumValues Enumerates the set of values for ListKeyVersionsSortByEnum
func GetListKeyVersionsSortByEnumValues() []ListKeyVersionsSortByEnum {
values := make([]ListKeyVersionsSortByEnum, 0)
for _, v := range mappingListKeyVersionsSortBy {
values = append(values, v)
}
return values
}
// ListKeyVersionsSortOrderEnum Enum with underlying type: string
type ListKeyVersionsSortOrderEnum string
// Set of constants representing the allowable values for ListKeyVersionsSortOrderEnum
const (
ListKeyVersionsSortOrderAsc ListKeyVersionsSortOrderEnum = "ASC"
ListKeyVersionsSortOrderDesc ListKeyVersionsSortOrderEnum = "DESC"
)
var mappingListKeyVersionsSortOrder = map[string]ListKeyVersionsSortOrderEnum{
"ASC": ListKeyVersionsSortOrderAsc,
"DESC": ListKeyVersionsSortOrderDesc,
}
// GetListKeyVersionsSortOrderEnumValues Enumerates the set of values for ListKeyVersionsSortOrderEnum
func GetListKeyVersionsSortOrderEnumValues() []ListKeyVersionsSortOrderEnum {
values := make([]ListKeyVersionsSortOrderEnum, 0)
for _, v := range mappingListKeyVersionsSortOrder {
values = append(values, v)
}
return values
}

View File

@@ -0,0 +1,129 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// ListKeysRequest wrapper for the ListKeys operation
type ListKeysRequest struct {
// The OCID of the compartment.
CompartmentId *string `mandatory:"true" contributesTo:"query" name:"compartmentId"`
// The maximum number of items to return in a paginated "List" call.
Limit *int `mandatory:"false" contributesTo:"query" name:"limit"`
// The value of the `opc-next-page` response header
// from the previous "List" call.
Page *string `mandatory:"false" contributesTo:"query" name:"page"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// The field to sort by. You can specify only one sort order. The default
// order for TIMECREATED is descending. The default order for DISPLAYNAME
// is ascending.
SortBy ListKeysSortByEnum `mandatory:"false" contributesTo:"query" name:"sortBy" omitEmpty:"true"`
// The sort order to use, either ascending (`ASC`) or descending (`DESC`).
SortOrder ListKeysSortOrderEnum `mandatory:"false" contributesTo:"query" name:"sortOrder" omitEmpty:"true"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ListKeysRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ListKeysRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ListKeysRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ListKeysResponse wrapper for the ListKeys operation
type ListKeysResponse struct {
// The underlying http response
RawResponse *http.Response
// A list of []KeySummary instances
Items []KeySummary `presentIn:"body"`
// For pagination of a list of items. When paging through a list, if this header appears in the response,
// then there are additional items still to get. Include this value as the `page` parameter for the
// subsequent GET request. For information about pagination, see
// List Pagination (https://docs.cloud.oracle.com/Content/API/Concepts/usingapi.htm#List_Pagination).
OpcNextPage *string `presentIn:"header" name:"opc-next-page"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ListKeysResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ListKeysResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
// ListKeysSortByEnum Enum with underlying type: string
type ListKeysSortByEnum string
// Set of constants representing the allowable values for ListKeysSortByEnum
const (
ListKeysSortByTimecreated ListKeysSortByEnum = "TIMECREATED"
ListKeysSortByDisplayname ListKeysSortByEnum = "DISPLAYNAME"
)
var mappingListKeysSortBy = map[string]ListKeysSortByEnum{
"TIMECREATED": ListKeysSortByTimecreated,
"DISPLAYNAME": ListKeysSortByDisplayname,
}
// GetListKeysSortByEnumValues Enumerates the set of values for ListKeysSortByEnum
func GetListKeysSortByEnumValues() []ListKeysSortByEnum {
values := make([]ListKeysSortByEnum, 0)
for _, v := range mappingListKeysSortBy {
values = append(values, v)
}
return values
}
// ListKeysSortOrderEnum Enum with underlying type: string
type ListKeysSortOrderEnum string
// Set of constants representing the allowable values for ListKeysSortOrderEnum
const (
ListKeysSortOrderAsc ListKeysSortOrderEnum = "ASC"
ListKeysSortOrderDesc ListKeysSortOrderEnum = "DESC"
)
var mappingListKeysSortOrder = map[string]ListKeysSortOrderEnum{
"ASC": ListKeysSortOrderAsc,
"DESC": ListKeysSortOrderDesc,
}
// GetListKeysSortOrderEnumValues Enumerates the set of values for ListKeysSortOrderEnum
func GetListKeysSortOrderEnumValues() []ListKeysSortOrderEnum {
values := make([]ListKeysSortOrderEnum, 0)
for _, v := range mappingListKeysSortOrder {
values = append(values, v)
}
return values
}

View File

@@ -0,0 +1,129 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// ListVaultsRequest wrapper for the ListVaults operation
type ListVaultsRequest struct {
// The OCID of the compartment.
CompartmentId *string `mandatory:"true" contributesTo:"query" name:"compartmentId"`
// The maximum number of items to return in a paginated "List" call.
Limit *int `mandatory:"false" contributesTo:"query" name:"limit"`
// The value of the `opc-next-page` response header
// from the previous "List" call.
Page *string `mandatory:"false" contributesTo:"query" name:"page"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// The field to sort by. You can specify only one sort order. The default
// order for TIMECREATED is descending. The default order for DISPLAYNAME
// is ascending.
SortBy ListVaultsSortByEnum `mandatory:"false" contributesTo:"query" name:"sortBy" omitEmpty:"true"`
// The sort order to use, either ascending (`ASC`) or descending (`DESC`).
SortOrder ListVaultsSortOrderEnum `mandatory:"false" contributesTo:"query" name:"sortOrder" omitEmpty:"true"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ListVaultsRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ListVaultsRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ListVaultsRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ListVaultsResponse wrapper for the ListVaults operation
type ListVaultsResponse struct {
// The underlying http response
RawResponse *http.Response
// A list of []VaultSummary instances
Items []VaultSummary `presentIn:"body"`
// For pagination of a list of items. When paging through a list, if this header appears in the response,
// then there are additional items still to get. Include this value as the `page` parameter for the
// subsequent GET request. For information about pagination, see
// List Pagination (https://docs.cloud.oracle.com/Content/API/Concepts/usingapi.htm#List_Pagination).
OpcNextPage *string `presentIn:"header" name:"opc-next-page"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ListVaultsResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ListVaultsResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
// ListVaultsSortByEnum Enum with underlying type: string
type ListVaultsSortByEnum string
// Set of constants representing the allowable values for ListVaultsSortByEnum
const (
ListVaultsSortByTimecreated ListVaultsSortByEnum = "TIMECREATED"
ListVaultsSortByDisplayname ListVaultsSortByEnum = "DISPLAYNAME"
)
var mappingListVaultsSortBy = map[string]ListVaultsSortByEnum{
"TIMECREATED": ListVaultsSortByTimecreated,
"DISPLAYNAME": ListVaultsSortByDisplayname,
}
// GetListVaultsSortByEnumValues Enumerates the set of values for ListVaultsSortByEnum
func GetListVaultsSortByEnumValues() []ListVaultsSortByEnum {
values := make([]ListVaultsSortByEnum, 0)
for _, v := range mappingListVaultsSortBy {
values = append(values, v)
}
return values
}
// ListVaultsSortOrderEnum Enum with underlying type: string
type ListVaultsSortOrderEnum string
// Set of constants representing the allowable values for ListVaultsSortOrderEnum
const (
ListVaultsSortOrderAsc ListVaultsSortOrderEnum = "ASC"
ListVaultsSortOrderDesc ListVaultsSortOrderEnum = "DESC"
)
var mappingListVaultsSortOrder = map[string]ListVaultsSortOrderEnum{
"ASC": ListVaultsSortOrderAsc,
"DESC": ListVaultsSortOrderDesc,
}
// GetListVaultsSortOrderEnumValues Enumerates the set of values for ListVaultsSortOrderEnum
func GetListVaultsSortOrderEnumValues() []ListVaultsSortOrderEnum {
values := make([]ListVaultsSortOrderEnum, 0)
for _, v := range mappingListVaultsSortOrder {
values = append(values, v)
}
return values
}

View File

@@ -0,0 +1,26 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// ScheduleKeyDeletionDetails Details for scheduling key deletion
type ScheduleKeyDeletionDetails struct {
// An optional property to indicate the deletion time of the key, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339)
// timestamp format. The specified time must be between 7 and 30 days from the time
// when the request is received. If this property is missing, it will be set to 30 days from the time of the request by default.
TimeOfDeletion *common.SDKTime `mandatory:"false" json:"timeOfDeletion"`
}
func (m ScheduleKeyDeletionDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,83 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// ScheduleKeyDeletionRequest wrapper for the ScheduleKeyDeletion operation
type ScheduleKeyDeletionRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// ScheduleKeyDeletionDetails
ScheduleKeyDeletionDetails `contributesTo:"body"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ScheduleKeyDeletionRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ScheduleKeyDeletionRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ScheduleKeyDeletionRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ScheduleKeyDeletionResponse wrapper for the ScheduleKeyDeletion operation
type ScheduleKeyDeletionResponse struct {
// The underlying http response
RawResponse *http.Response
// The Key instance
Key `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ScheduleKeyDeletionResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ScheduleKeyDeletionResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,26 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// ScheduleVaultDeletionDetails Details for scheduling vault deletion
type ScheduleVaultDeletionDetails struct {
// An optional property to indicate the deletion time of the vault, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339)
// timestamp format. The specified time must be between 7 and 30 days from the time
// when the request is received. If this property is missing, it will be set to 30 days from the time of the request by default.
TimeOfDeletion *common.SDKTime `mandatory:"false" json:"timeOfDeletion"`
}
func (m ScheduleVaultDeletionDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,83 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// ScheduleVaultDeletionRequest wrapper for the ScheduleVaultDeletion operation
type ScheduleVaultDeletionRequest struct {
// The OCID of the vault.
VaultId *string `mandatory:"true" contributesTo:"path" name:"vaultId"`
// ScheduleVaultDeletionDetails
ScheduleVaultDeletionDetails `contributesTo:"body"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// A token that uniquely identifies a request so it can be retried in case
// of a timeout or server error without risk of executing that same action
// again. Retry tokens expire after 24 hours, but can be invalidated
// before then due to conflicting operations (e.g., if a resource has been
// deleted and purged from the system, then a retry of the original
// creation request may be rejected).
OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ScheduleVaultDeletionRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ScheduleVaultDeletionRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ScheduleVaultDeletionRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ScheduleVaultDeletionResponse wrapper for the ScheduleVaultDeletion operation
type ScheduleVaultDeletionResponse struct {
// The underlying http response
RawResponse *http.Response
// The Vault instance
Vault `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ScheduleVaultDeletionResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ScheduleVaultDeletionResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,34 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// UpdateKeyDetails The representation of UpdateKeyDetails
type UpdateKeyDetails struct {
// Usage of predefined tag keys. These predefined keys are scoped to namespaces.
// Example: `{"foo-namespace": {"bar-key": "foo-value"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// A user-friendly name for the key. It does not have to be unique, and it is changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Simple key-value pair that is applied without any predefined name, type, or scope.
// Exists for cross-compatibility only.
// Example: `{"bar-key": "value"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
}
func (m UpdateKeyDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,75 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// UpdateKeyRequest wrapper for the UpdateKey operation
type UpdateKeyRequest struct {
// The OCID of the key.
KeyId *string `mandatory:"true" contributesTo:"path" name:"keyId"`
// UpdateKeyDetails
UpdateKeyDetails `contributesTo:"body"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request UpdateKeyRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request UpdateKeyRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request UpdateKeyRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// UpdateKeyResponse wrapper for the UpdateKey operation
type UpdateKeyResponse struct {
// The underlying http response
RawResponse *http.Response
// The Key instance
Key `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response UpdateKeyResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response UpdateKeyResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,34 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// UpdateVaultDetails The representation of UpdateVaultDetails
type UpdateVaultDetails struct {
// Usage of predefined tag keys. These predefined keys are scoped to namespaces.
// Example: `{"foo-namespace": {"bar-key": "foo-value"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// A user-friendly name for the vault. It does not have to be unique, and it is changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"false" json:"displayName"`
// Simple key-value pair that is applied without any predefined name, type, or scope.
// Exists for cross-compatibility only.
// Example: `{"bar-key": "value"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
}
func (m UpdateVaultDetails) String() string {
return common.PointerString(m)
}

View File

@@ -0,0 +1,75 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
"net/http"
)
// UpdateVaultRequest wrapper for the UpdateVault operation
type UpdateVaultRequest struct {
// The OCID of the vault.
VaultId *string `mandatory:"true" contributesTo:"path" name:"vaultId"`
// UpdateVaultDetails
UpdateVaultDetails `contributesTo:"body"`
// For optimistic concurrency control. In the PUT or DELETE call for a
// resource, set the `if-match` parameter to the value of the etag from a
// previous GET or POST response for that resource. The resource will be
// updated or deleted only if the etag you provide matches the resource's
// current etag value.
IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`
// Unique identifier for the request. If provided, the returned request ID
// will include this value. Otherwise, a random request ID will be
// generated by the service.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request UpdateVaultRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request UpdateVaultRequest) HTTPRequest(method, path string) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request UpdateVaultRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// UpdateVaultResponse wrapper for the UpdateVault operation
type UpdateVaultResponse struct {
// The underlying http response
RawResponse *http.Response
// The Vault instance
Vault `presentIn:"body"`
// For optimistic concurrency control. See `if-match`.
Etag *string `presentIn:"header" name:"etag"`
// Unique Oracle-assigned identifier for the request. If you need to contact Oracle about
// a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response UpdateVaultResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response UpdateVaultResponse) HTTPResponse() *http.Response {
return response.RawResponse
}

View File

@@ -0,0 +1,117 @@
// Copyright (c) 2016, 2018, 2019, Oracle and/or its affiliates. All rights reserved.
// Code generated. DO NOT EDIT.
// Key Management Service API
//
// API for managing and performing operations with keys and vaults.
//
package keymanagement
import (
"github.com/oracle/oci-go-sdk/common"
)
// Vault The representation of Vault
type Vault struct {
// The OCID of the compartment that contains this vault.
CompartmentId *string `mandatory:"true" json:"compartmentId"`
// The service endpoint to perform cryptographic operations against. Cryptographic operations include 'Encrypt,' 'Decrypt,' and 'GenerateDataEncryptionKey' operations.
CryptoEndpoint *string `mandatory:"true" json:"cryptoEndpoint"`
// A user-friendly name for the vault. It does not have to be unique, and it is changeable.
// Avoid entering confidential information.
DisplayName *string `mandatory:"true" json:"displayName"`
// The OCID of the vault.
Id *string `mandatory:"true" json:"id"`
// The vault's current state.
// Example: `DELETED`
LifecycleState VaultLifecycleStateEnum `mandatory:"true" json:"lifecycleState"`
// The service endpoint to perform management operations against. Management operations include 'Create,' 'Update,' 'List,' 'Get,' and 'Delete' operations.
ManagementEndpoint *string `mandatory:"true" json:"managementEndpoint"`
// The date and time this vault was created, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format.
// Example: `2018-04-03T21:10:29.600Z`
TimeCreated *common.SDKTime `mandatory:"true" json:"timeCreated"`
// The type of vault. Each type of vault stores the key with different degrees of isolation and has different options and pricing.
VaultType VaultVaultTypeEnum `mandatory:"true" json:"vaultType"`
// Usage of predefined tag keys. These predefined keys are scoped to namespaces.
// Example: `{"foo-namespace": {"bar-key": "foo-value"}}`
DefinedTags map[string]map[string]interface{} `mandatory:"false" json:"definedTags"`
// Simple key-value pair that is applied without any predefined name, type, or scope.
// Exists for cross-compatibility only.
// Example: `{"bar-key": "value"}`
FreeformTags map[string]string `mandatory:"false" json:"freeformTags"`
// An optional property for the deletion time of the vault, expressed in RFC 3339 (https://tools.ietf.org/html/rfc3339) timestamp format.
// Example: `2018-04-03T21:10:29.600Z`
TimeOfDeletion *common.SDKTime `mandatory:"false" json:"timeOfDeletion"`
}
func (m Vault) String() string {
return common.PointerString(m)
}
// VaultLifecycleStateEnum Enum with underlying type: string
type VaultLifecycleStateEnum string
// Set of constants representing the allowable values for VaultLifecycleStateEnum
const (
VaultLifecycleStateCreating VaultLifecycleStateEnum = "CREATING"
VaultLifecycleStateActive VaultLifecycleStateEnum = "ACTIVE"
VaultLifecycleStateDeleting VaultLifecycleStateEnum = "DELETING"
VaultLifecycleStateDeleted VaultLifecycleStateEnum = "DELETED"
VaultLifecycleStatePendingDeletion VaultLifecycleStateEnum = "PENDING_DELETION"
VaultLifecycleStateSchedulingDeletion VaultLifecycleStateEnum = "SCHEDULING_DELETION"
VaultLifecycleStateCancellingDeletion VaultLifecycleStateEnum = "CANCELLING_DELETION"
VaultLifecycleStateUpdating VaultLifecycleStateEnum = "UPDATING"
)
var mappingVaultLifecycleState = map[string]VaultLifecycleStateEnum{
"CREATING": VaultLifecycleStateCreating,
"ACTIVE": VaultLifecycleStateActive,
"DELETING": VaultLifecycleStateDeleting,
"DELETED": VaultLifecycleStateDeleted,
"PENDING_DELETION": VaultLifecycleStatePendingDeletion,
"SCHEDULING_DELETION": VaultLifecycleStateSchedulingDeletion,
"CANCELLING_DELETION": VaultLifecycleStateCancellingDeletion,
"UPDATING": VaultLifecycleStateUpdating,
}
// GetVaultLifecycleStateEnumValues Enumerates the set of values for VaultLifecycleStateEnum
func GetVaultLifecycleStateEnumValues() []VaultLifecycleStateEnum {
values := make([]VaultLifecycleStateEnum, 0)
for _, v := range mappingVaultLifecycleState {
values = append(values, v)
}
return values
}
// VaultVaultTypeEnum Enum with underlying type: string
type VaultVaultTypeEnum string
// Set of constants representing the allowable values for VaultVaultTypeEnum
const (
VaultVaultTypePrivate VaultVaultTypeEnum = "VIRTUAL_PRIVATE"
)
var mappingVaultVaultType = map[string]VaultVaultTypeEnum{
"VIRTUAL_PRIVATE": VaultVaultTypePrivate,
}
// GetVaultVaultTypeEnumValues Enumerates the set of values for VaultVaultTypeEnum
func GetVaultVaultTypeEnumValues() []VaultVaultTypeEnum {
values := make([]VaultVaultTypeEnum, 0)
for _, v := range mappingVaultVaultType {
values = append(values, v)
}
return values
}

Some files were not shown because too many files have changed in this diff Show More