├── LICENSE ├── README.md ├── bin ├── build └── integration-tests ├── credentials.go ├── go.mod ├── go.sum ├── main.go ├── metadata.go └── token.go /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # container-instance-metadata-server 2 | 3 | The `container-instance-metadata-server` emulates the Cloud Run [container instance metadata server](https://cloud.google.com/run/docs/reference/container-contract#metadata-server) for a given [service account](https://cloud.google.com/iam/docs/service-accounts) and user supplied metadata. 4 | 5 | Service accounts are [impersonated](https://cloud.google.com/iam/docs/understanding-service-accounts) using the [application default credentials](https://cloud.google.com/iam/docs/service-accounts#application_default_credentials) set by the `gcloud` commandline tool. 6 | 7 | ``` 8 | gcloud auth application-default login 9 | ``` 10 | 11 | ## Available metadata server information 12 | 13 | ``` 14 | /computeMetadata/v1/instance/id 15 | /computeMetadata/v1/instance/service-accounts/default/aliases 16 | /computeMetadata/v1/instance/service-accounts/default/email 17 | /computeMetadata/v1/instance/service-accounts/default/token 18 | /computeMetadata/v1/instance/service-accounts/default/identity 19 | /computeMetadata/v1/instance/region 20 | /computeMetadata/v1/instance/zone 21 | /computeMetadata/v1/project/numeric-project-id 22 | /computeMetadata/v1/project/project-id 23 | ``` 24 | 25 | ## Usage 26 | 27 | When running the emulator locally be sure to disable the `gcloud` metadata checks: 28 | 29 | ``` 30 | gcloud config set check_gce_metadata False 31 | ``` 32 | 33 | Start the metadata service: 34 | 35 | ``` 36 | container-instance-metadata-server -h 37 | ``` 38 | ``` 39 | Usage of container-instance-metadata-server: 40 | -google-application-credentials string 41 | Default service account file path 42 | -listen-address string 43 | The HTTP listen address (default "127.0.0.1:8888") 44 | -metadata string 45 | Metadata file path (default "metadata.json") 46 | -service-account string 47 | The email address of an IAM service account 48 | ``` 49 | 50 | ## Tutorial 51 | 52 | Create a metadata configuration file: 53 | 54 | ``` 55 | PROJECT_ID=$(gcloud config get-value project) 56 | ``` 57 | 58 | ``` 59 | PROJECT_NUMBER=$(gcloud projects describe ${PROJECT_ID} --format="value(projectNumber)") 60 | ``` 61 | 62 | ``` 63 | cat < metadata.json 64 | { 65 | "instance": { 66 | "region": "us-west1" 67 | }, 68 | "project": { 69 | "numeric_project_id": "${PROJECT_NUMBER}", 70 | "project_id": "${PROJECT_ID}" 71 | } 72 | } 73 | EOF 74 | ``` 75 | 76 | Create the IAM service account that will be impersonated when generating access and identity tokens: 77 | 78 | ``` 79 | gcloud iam service-accounts create metadata-server 80 | ``` 81 | 82 | Create an IAM policy to grant the current logged in user the ability to impersonate the `metadata-server` service account: 83 | 84 | ``` 85 | cat < policy.yaml 86 | bindings: 87 | - role: "roles/iam.serviceAccountTokenCreator" 88 | members: 89 | - "user:$(gcloud config get-value account)" 90 | EOF 91 | ``` 92 | 93 | Apply the IAM policy: 94 | 95 | ``` 96 | gcloud -q iam service-accounts set-iam-policy \ 97 | "metadata-server@${PROJECT_ID}.iam.gserviceaccount.com" \ 98 | policy.yaml 99 | ``` 100 | 101 | At this point you have the ability to impersonate the `metadata-server` service account. 102 | 103 | > It may take a few minutes for the changes to take effect. 104 | 105 | Start the `container-instance-metadata-server`: 106 | 107 | ``` 108 | container-instance-metadata-server \ 109 | --metadata metadata.json \ 110 | --service-account "metadata-server@${PROJECT_ID}.iam.gserviceaccount.com" 111 | ``` 112 | 113 | ``` 114 | 2020/10/13 00:16:07 Starting Container Instance Metadata Service ... 115 | 2020/10/13 00:16:07 Impersonating metadata-server@hightowerlabs.iam.gserviceaccount.com 116 | 2020/10/13 00:16:07 Listening on 127.0.0.1:8888 117 | ``` 118 | 119 | ### Test 120 | 121 | Retrieve the `instance/region` metadata key: 122 | 123 | ``` 124 | curl -i http://127.0.0.1:8888/computeMetadata/v1/instance/region \ 125 | -H "Metadata-Flavor: Google" 126 | ``` 127 | 128 | ``` 129 | HTTP/1.1 200 OK 130 | Content-Type: application/text 131 | Metadata-Flavor: Google 132 | Server: Metadata Server for Serverless 133 | Date: Mon, 12 Oct 2020 09:35:28 GMT 134 | Content-Length: 8 135 | 136 | us-west1 137 | ``` 138 | 139 | Generate an access token: 140 | 141 | ``` 142 | curl -i -G http://127.0.0.1:8888/computeMetadata/v1/instance/service-accounts/default/token \ 143 | -H "Metadata-Flavor: Google" \ 144 | --data-urlencode 'scopes=https://www.googleapis.com/auth/cloud-platform' 145 | ``` 146 | 147 | ``` 148 | HTTP/1.1 200 OK 149 | Content-Type: application/json 150 | Metadata-Flavor: Google 151 | Server: Metadata Server for Serverless 152 | Date: Tue, 13 Oct 2020 08:51:25 GMT 153 | Content-Length: 453 154 | 155 | {"access_token":"redacted","expires_in":3599,"token_type":"Bearer"} 156 | ``` 157 | 158 | ## Configuration 159 | 160 | * `instance.region` string 161 | * `project.numeric_project_id` string 162 | * `project.project_id` string 163 | 164 | ### Example 165 | 166 | ```json 167 | { 168 | "instance": { 169 | "region": "us-west1" 170 | }, 171 | "project": { 172 | "numeric_project_id": "330612842442", 173 | "project_id": "hightowerlabs" 174 | } 175 | } 176 | ``` 177 | 178 | ## Routing Traffic 179 | 180 | You can also run the metadata server on the same address `169.254.169.254` as Cloud Run does and also map the `metadata.google.internal` domain to that address. 181 | 182 | Add a secondary IP address: 183 | 184 | ``` 185 | sudo ip address add 169.254.169.254/24 dev eth0 186 | ``` 187 | 188 | Append the following line to `/etc/hosts`: 189 | 190 | ``` 191 | 169.254.169.254 metadata.google.internal 192 | ``` 193 | 194 | Resolve `metadata.google.internal`: 195 | 196 | ``` 197 | getent hosts metadata.google.internal 198 | ``` 199 | 200 | ``` 201 | 169.254.169.254 metadata.google.internal 202 | ``` 203 | 204 | Start the `container-instance-metadata-server`: 205 | 206 | ``` 207 | sudo container-instance-metadata-server \ 208 | --google-application-credentials ${HOME}/.config/gcloud/application_default_credentials.json \ 209 | --listen-address "169.254.169.254:80" \ 210 | --metadata metadata.json \ 211 | --service-account "metadata-server@${PROJECT_ID}.iam.gserviceaccount.com" 212 | ``` 213 | 214 | > Use the `--google-application-credentials` flag to use the current user's default service account. 215 | 216 | ### Test 217 | 218 | ``` 219 | curl -i http://metadata.google.internal/computeMetadata/v1/instance/id \ 220 | -H "Metadata-Flavor: Google" 221 | ``` 222 | 223 | ``` 224 | HTTP/1.1 200 OK 225 | Content-Type: application/text 226 | Metadata-Flavor: Google 227 | Server: Metadata Server for Serverless 228 | Date: Tue, 13 Oct 2020 08:52:52 GMT 229 | Content-Length: 128 230 | 231 | e368815d7aa80123751793efb5c86401d81edc3205f14ae196732d13805adcc65b38d1ef882a877a36526a52437acf3bc03c7b3f3bd7029e08020615724d7b74 232 | ``` 233 | 234 | > The id is auto generated by `container-instance-metadata-server` at start up. 235 | -------------------------------------------------------------------------------- /bin/build: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \ 4 | go build -a -tags netgo \ 5 | -ldflags '-w -extldflags "-static"' \ 6 | -o container-instance-metadata-server 7 | -------------------------------------------------------------------------------- /bin/integration-tests: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ENDPOINT="127.0.0.1:8888" 4 | 5 | curl -i "http://${ENDPOINT}/computeMetadata/v1/instance/service-accounts/default/aliases" \ 6 | -H "Metadata-Flavor: Google" 7 | echo "" 8 | 9 | curl -i "http://${ENDPOINT}/computeMetadata/v1/instance/service-accounts/default/email" \ 10 | -H "Metadata-Flavor: Google" 11 | echo "" 12 | 13 | curl -i "http://${ENDPOINT}/computeMetadata/v1/instance/service-accounts/default/identity?audience=https://example.org" \ 14 | -H "Metadata-Flavor: Google" 15 | echo "" 16 | 17 | curl -i "http://${ENDPOINT}/computeMetadata/v1/instance/service-accounts/default/token?scopes=https://www.googleapis.com/auth/cloud-platform" \ 18 | -H "Metadata-Flavor: Google" 19 | echo "" 20 | 21 | curl -i "http://${ENDPOINT}/computeMetadata/v1/instance/id" \ 22 | -H "Metadata-Flavor: Google" 23 | echo "" 24 | 25 | curl -i "http://${ENDPOINT}/computeMetadata/v1/instance/region" \ 26 | -H "Metadata-Flavor: Google" 27 | echo "" 28 | 29 | curl -i "http://${ENDPOINT}/computeMetadata/v1/instance/zone" \ 30 | -H "Metadata-Flavor: Google" 31 | echo "" 32 | 33 | curl -i "http://${ENDPOINT}/computeMetadata/v1/project/numeric-project-id" \ 34 | -H "Metadata-Flavor: Google" 35 | echo "" 36 | 37 | curl -i "http://${ENDPOINT}/computeMetadata/v1/project/project-id" \ 38 | -H "Metadata-Flavor: Google" 39 | echo "" 40 | -------------------------------------------------------------------------------- /credentials.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | "os/user" 9 | "path/filepath" 10 | ) 11 | 12 | type Credentials struct { 13 | ClientID string `json:"client_id"` 14 | ClientSecret string `json:"client_secret"` 15 | QuotaProjectID string `json:"quota_project_id"` 16 | RefreshToken string `json:"refresh_token"` 17 | Type string `json:"type"` 18 | } 19 | 20 | type ServiceAccount struct { 21 | Type string `json:"type"` 22 | ClientEmail string `json:"client_email"` 23 | PrivateKeyID string `json:"private_key_id"` 24 | PrivateKey string `json:"private_key"` 25 | TokenURL string `json:"token_uri"` 26 | ProjectID string `json:"project_id"` 27 | } 28 | 29 | func CredentialsFromFile() (*Credentials, error) { 30 | f := wellKnownFile() 31 | data, err := ioutil.ReadFile(f) 32 | if err != nil { 33 | return nil, fmt.Errorf("Unable to read credentials file: %w", err) 34 | } 35 | 36 | var c Credentials 37 | if err := json.Unmarshal(data, &c); err != nil { 38 | return nil, fmt.Errorf("Unable to parse credentials file: %w", err) 39 | } 40 | 41 | return &c, nil 42 | } 43 | 44 | func ServiceAccountFromFile(path string) (*ServiceAccount, error) { 45 | data, err := ioutil.ReadFile(path) 46 | if err != nil { 47 | return nil, fmt.Errorf("Unable to read service account file: %w", err) 48 | } 49 | 50 | var sa ServiceAccount 51 | if err := json.Unmarshal(data, &sa); err != nil { 52 | return nil, fmt.Errorf("Unable to parse service account file: %w", err) 53 | } 54 | 55 | return &sa, nil 56 | } 57 | 58 | func wellKnownFile() string { 59 | if defaultCredentials != "" { 60 | return defaultCredentials 61 | } 62 | 63 | homeDir := os.Getenv("HOME") 64 | if homeDir == "" { 65 | if u, err := user.Current(); err == nil { 66 | homeDir = u.HomeDir 67 | } 68 | } 69 | return filepath.Join(homeDir, ".config", "gcloud", "application_default_credentials.json") 70 | } 71 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/kelseyhightower/container-instance-metadata-server 2 | 3 | go 1.15 4 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kelseyhightower/container-instance-metadata-server/4dfb528d335dde9207ea54771205ae462277a412/go.sum -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "strings" 9 | ) 10 | 11 | var ( 12 | defaultCredentials string 13 | metadataFile string 14 | serviceAccountEmail string 15 | listenAddress string 16 | ) 17 | 18 | func main() { 19 | flag.StringVar(&defaultCredentials, "google-application-credentials", "", "Default service account file path") 20 | flag.StringVar(&listenAddress, "listen-address", "127.0.0.1:8888", "The HTTP listen address") 21 | flag.StringVar(&metadataFile, "metadata", "metadata.json", "Metadata file path") 22 | flag.StringVar(&serviceAccountEmail, "service-account", "", "The email address of an IAM service account") 23 | flag.Parse() 24 | 25 | log.Println("Starting Container Instance Metadata Service ...") 26 | log.Printf("Impersonating %s", serviceAccountEmail) 27 | log.Printf("Listening on %s", listenAddress) 28 | 29 | md, err := MetadataFromFile(metadataFile) 30 | if err != nil { 31 | log.Fatal(err) 32 | } 33 | 34 | http.Handle("/", &metadataHandler{md, serviceAccountEmail}) 35 | 36 | log.Fatal(http.ListenAndServe(listenAddress, nil)) 37 | } 38 | 39 | type metadataHandler struct { 40 | md *Metadata 41 | sa string 42 | } 43 | 44 | func (h *metadataHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { 45 | log.Printf("Handling request for %s", r.URL.RequestURI()) 46 | 47 | w.Header().Set("Metadata-Flavor", "Google") 48 | w.Header().Set("Server", "Metadata Server for Serverless") 49 | w.Header().Set("Content-Type", "application/text") 50 | 51 | if r.Header.Get("Metadata-Flavor") != "Google" { 52 | w.Header().Set("Content-Type", "text/html; charset=UTF-8") 53 | w.WriteHeader(403) 54 | return 55 | } 56 | 57 | switch r.URL.Path { 58 | case "/computeMetadata/v1/instance/id": 59 | fmt.Fprintf(w, h.md.Instance.ID) 60 | case "/computeMetadata/v1/instance/service-accounts/default/aliases": 61 | fmt.Fprintf(w, "default") 62 | case "/computeMetadata/v1/instance/service-accounts/default/email": 63 | fmt.Fprintf(w, h.sa) 64 | case "/computeMetadata/v1/instance/service-accounts/default/token": 65 | scopes := strings.Split(r.URL.Query().Get("scopes"), ",") 66 | 67 | token, err := generateAccessToken(h.sa, scopes) 68 | if err != nil { 69 | log.Println(err) 70 | http.Error(w, err.Error(), 500) 71 | return 72 | } 73 | 74 | w.Header().Set("Content-Type", "application/json") 75 | w.Write(token) 76 | case "/computeMetadata/v1/instance/service-accounts/default/identity": 77 | audience := r.URL.Query().Get("audience") 78 | token, err := generateIdToken(h.sa, audience) 79 | if err != nil { 80 | log.Println(err) 81 | http.Error(w, err.Error(), 500) 82 | return 83 | } 84 | fmt.Fprintf(w, token) 85 | case "/computeMetadata/v1/instance/region": 86 | fmt.Fprintf(w, h.md.Instance.Region) 87 | case "/computeMetadata/v1/instance/zone": 88 | fmt.Fprintf(w, "projects/%s/zones/%s-1", h.md.Project.NumericProjectID, h.md.Instance.Region) 89 | case "/computeMetadata/v1/project/numeric-project-id": 90 | fmt.Fprintf(w, h.md.Project.NumericProjectID) 91 | case "/computeMetadata/v1/project/project-id": 92 | fmt.Fprintf(w, h.md.Project.ProjectID) 93 | default: 94 | w.Header().Set("Content-Type", "text/html; charset=UTF-8") 95 | http.NotFound(w, r) 96 | return 97 | } 98 | 99 | return 100 | } 101 | -------------------------------------------------------------------------------- /metadata.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/sha512" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "io/ioutil" 9 | "time" 10 | ) 11 | 12 | type Metadata struct { 13 | Instance InstanceMetadata `json:"instance"` 14 | Project ProjectMetadata `json:"project"` 15 | } 16 | 17 | type InstanceMetadata struct { 18 | ID string `json:"id"` 19 | Region string `json:"region"` 20 | } 21 | 22 | type ProjectMetadata struct { 23 | NumericProjectID string `json:"numeric_project_id"` 24 | ProjectID string `json:"project_id"` 25 | } 26 | 27 | func MetadataFromFile(path string) (*Metadata, error) { 28 | if path == "" { 29 | return nil, errors.New("metadata file required.") 30 | } 31 | 32 | data, err := ioutil.ReadFile(path) 33 | if err != nil { 34 | return nil, err 35 | } 36 | 37 | var m Metadata 38 | if err := json.Unmarshal(data, &m); err != nil { 39 | return nil, err 40 | } 41 | 42 | if m.Instance.ID == "" { 43 | m.Instance.ID = generateInstanceID() 44 | } 45 | 46 | return &m, nil 47 | } 48 | 49 | func generateInstanceID() string { 50 | now := time.Now().String() 51 | return fmt.Sprintf("%x", sha512.Sum512([]byte(now))) 52 | } 53 | -------------------------------------------------------------------------------- /token.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io/ioutil" 8 | "net/http" 9 | "net/url" 10 | "strings" 11 | "time" 12 | ) 13 | 14 | var ( 15 | tokenEndpoint = "https://oauth2.googleapis.com/token" 16 | iamcredentialsEndpoint = "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts" 17 | ) 18 | 19 | type Token struct { 20 | AccessToken string `json:"access_token"` 21 | ExpiresIn int `json:"expires_in"` 22 | IDToken string `json:"id_token"` 23 | Scope string `json:"scope"` 24 | TokenType string `json:"token_type"` 25 | } 26 | 27 | type AccessTokenRequest struct { 28 | Scope []string `json:"scope"` 29 | } 30 | 31 | type AccessTokenResponse struct { 32 | AccessToken string `json:"accessToken"` 33 | ExpireTime time.Time `json:"expireTime"` 34 | } 35 | 36 | type IDTokenRequest struct { 37 | Audience string `json:"audience"` 38 | IncludeEmail string `json:"includeEmail"` 39 | } 40 | 41 | type IDTokenResponse struct { 42 | Token string `json:"token"` 43 | } 44 | 45 | func accessToken() (*Token, error) { 46 | credentials, err := CredentialsFromFile() 47 | if err != nil { 48 | return nil, err 49 | } 50 | 51 | v := url.Values{} 52 | v.Set("grant_type", "refresh_token") 53 | v.Set("client_id", credentials.ClientID) 54 | v.Set("client_secret", credentials.ClientSecret) 55 | v.Set("refresh_token", credentials.RefreshToken) 56 | 57 | request, err := http.NewRequest("POST", tokenEndpoint, strings.NewReader(v.Encode())) 58 | if err != nil { 59 | return nil, err 60 | } 61 | 62 | request.Header.Set("Content-Type", "application/x-www-form-urlencoded") 63 | 64 | client := &http.Client{} 65 | 66 | response, err := client.Do(request) 67 | if err != nil { 68 | return nil, err 69 | } 70 | 71 | data, err := ioutil.ReadAll(response.Body) 72 | if err != nil { 73 | return nil, err 74 | } 75 | 76 | defer response.Body.Close() 77 | 78 | if response.StatusCode != 200 { 79 | return nil, fmt.Errorf("error generating user access token: %d", response.StatusCode) 80 | } 81 | 82 | var t Token 83 | if err := json.Unmarshal(data, &t); err != nil { 84 | return nil, err 85 | } 86 | 87 | return &t, nil 88 | } 89 | 90 | func generateIdToken(sa, audience string) (string, error) { 91 | token, err := accessToken() 92 | if err != nil { 93 | return "", err 94 | } 95 | 96 | idTokenRequest := IDTokenRequest{ 97 | Audience: audience, 98 | IncludeEmail: "false", 99 | } 100 | 101 | data, err := json.Marshal(idTokenRequest) 102 | if err != nil { 103 | return "", err 104 | } 105 | 106 | endpoint := fmt.Sprintf("%s/%s:generateIdToken", iamcredentialsEndpoint, sa) 107 | 108 | request, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(data)) 109 | if err != nil { 110 | return "", err 111 | } 112 | 113 | request.Header.Set("Content-Type", "application/json; charset=utf-8") 114 | request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken)) 115 | 116 | client := &http.Client{} 117 | 118 | response, err := client.Do(request) 119 | if err != nil { 120 | return "", err 121 | } 122 | 123 | data, err = ioutil.ReadAll(response.Body) 124 | if err != nil { 125 | return "", err 126 | } 127 | 128 | defer response.Body.Close() 129 | 130 | if response.StatusCode != 200 { 131 | return "", fmt.Errorf("error generating id token: %d", response.StatusCode) 132 | } 133 | 134 | var idt IDTokenResponse 135 | if err := json.Unmarshal(data, &idt); err != nil { 136 | return "", err 137 | } 138 | 139 | return idt.Token, nil 140 | } 141 | 142 | type AccessTokenMetadataResponse struct { 143 | AccessToken string `json:"access_token"` 144 | Expiry int64 `json:"expires_in"` 145 | TokenType string `json:"token_type"` 146 | } 147 | 148 | func generateAccessToken(sa string, scopes []string) ([]byte, error) { 149 | token, err := accessToken() 150 | if err != nil { 151 | return nil, err 152 | } 153 | 154 | accessTokenRequest := AccessTokenRequest{ 155 | Scope: scopes, 156 | } 157 | 158 | data, err := json.Marshal(accessTokenRequest) 159 | if err != nil { 160 | return nil, err 161 | } 162 | 163 | endpoint := fmt.Sprintf("%s/%s:generateAccessToken", iamcredentialsEndpoint, sa) 164 | 165 | request, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(data)) 166 | if err != nil { 167 | return nil, err 168 | } 169 | 170 | request.Header.Set("Content-Type", "application/json; charset=utf-8") 171 | request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken)) 172 | 173 | client := &http.Client{} 174 | 175 | response, err := client.Do(request) 176 | if err != nil { 177 | return nil, err 178 | } 179 | 180 | data, err = ioutil.ReadAll(response.Body) 181 | if err != nil { 182 | return nil, err 183 | } 184 | 185 | defer response.Body.Close() 186 | 187 | if response.StatusCode != 200 { 188 | return nil, fmt.Errorf("error generating id token: %d", response.StatusCode) 189 | } 190 | 191 | var a AccessTokenResponse 192 | if err := json.Unmarshal(data, &a); err != nil { 193 | return nil, err 194 | } 195 | 196 | md := AccessTokenMetadataResponse{ 197 | AccessToken: a.AccessToken, 198 | Expiry: int64(time.Until(a.ExpireTime).Seconds()), 199 | TokenType: "Bearer", 200 | } 201 | 202 | data, err = json.Marshal(md) 203 | if err != nil { 204 | return nil, err 205 | } 206 | 207 | return data, nil 208 | } 209 | --------------------------------------------------------------------------------