-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add signed-metadata example #828
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# Verify instance identity Java sample for Google Compute Engine | ||
|
||
This repository contains example code in Java that downloads and verifies JWT | ||
provided by metadata endpoint, which is available on Compute Engine instances in | ||
GCP. | ||
|
||
More about this verification can be read on official Google Cloud documentation | ||
[Veryfying the Identity of | ||
Instances](https://cloud.google.com/compute/docs/instances/verifying-instance-identity). | ||
|
||
## Running on Compute Engine | ||
|
||
To run the sample, you will need to do the following: | ||
|
||
1. Create a compute instance on the Google Cloud Platform Developer's Console | ||
1. SSH into the instance you created | ||
1. Update packages and install required packages | ||
|
||
`sudo apt-get update && sudo apt-get install git-core openjdk-8-jdk maven` | ||
|
||
1. Clone the repo | ||
|
||
`git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git` | ||
|
||
1. Navigate to `java-docs-samples/compute/signed-metadata/` | ||
|
||
`cd java-docs-samples/compute/signed-metadata/` | ||
|
||
1. Use maven to package the class as a jar | ||
|
||
`mvn clean package` | ||
|
||
1. Make sure that openjdk 8 is the selected java version | ||
|
||
`sudo update-alternatives --config java` | ||
|
||
1. Execute the jar file | ||
|
||
`java -jar target/compute-signed-metadata-1.0-SNAPSHOT-jar-with-dependencies.jar` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
<!-- | ||
Copyright 2016 Google Inc. | ||
|
||
Licensed under the Apache License, Version 2.0 (the "License"); | ||
you may not use this file except in compliance with the License. | ||
You may obtain a copy of the License at | ||
|
||
http://www.apache.org/licenses/LICENSE-2.0 | ||
|
||
Unless required by applicable law or agreed to in writing, software | ||
distributed under the License is distributed on an "AS IS" BASIS, | ||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
See the License for the specific language governing permissions and | ||
limitations under the License. | ||
--> | ||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> | ||
<modelVersion>4.0.0</modelVersion> | ||
<groupId>com.google.cloud.example.jwt</groupId> | ||
<artifactId>compute-signed-metadata</artifactId> | ||
<version>1.0-SNAPSHOT</version> | ||
<name>compute-signed-metadata</name> | ||
<parent> | ||
<groupId>com.google.cloud</groupId> | ||
<artifactId>compute</artifactId> | ||
<version>1.0.0</version> | ||
<relativePath>..</relativePath> | ||
</parent> | ||
<dependencies> | ||
<dependency> | ||
<groupId>com.auth0</groupId> | ||
<artifactId>java-jwt</artifactId> | ||
<version>3.2.0</version> | ||
</dependency> | ||
<dependency> | ||
<groupId>com.google.code.gson</groupId> | ||
<artifactId>gson</artifactId> | ||
<version>2.8.1</version> | ||
</dependency> | ||
<dependency> | ||
<groupId>com.google.guava</groupId> | ||
<artifactId>guava</artifactId> | ||
<version>23.0</version> | ||
</dependency> | ||
</dependencies> | ||
<build> | ||
<plugins> | ||
<plugin> | ||
<groupId>org.apache.maven.plugins</groupId> | ||
<artifactId>maven-jar-plugin</artifactId> | ||
<version>3.0.2</version> | ||
</plugin> | ||
<plugin> | ||
<groupId>org.apache.maven.plugins</groupId> | ||
<artifactId>maven-assembly-plugin</artifactId> | ||
<version>3.0.0</version> | ||
<executions> | ||
<execution> | ||
<phase>package</phase> | ||
<goals> | ||
<goal>single</goal> | ||
</goals> | ||
</execution> | ||
</executions> | ||
<configuration> | ||
<archive> | ||
<manifest> | ||
<mainClass>com.example.compute.signedmetadata.App</mainClass> | ||
</manifest> | ||
</archive> | ||
<descriptorRefs> | ||
<descriptorRef>jar-with-dependencies</descriptorRef> | ||
</descriptorRefs> | ||
</configuration> | ||
</plugin> | ||
<plugin> | ||
<groupId>org.apache.maven.plugins</groupId> | ||
<artifactId>maven-compiler-plugin</artifactId> | ||
<version>3.6.2</version> | ||
<configuration> | ||
<source>1.8</source> | ||
<target>1.8</target> | ||
</configuration> | ||
</plugin> | ||
</plugins> | ||
</build> | ||
</project> |
28 changes: 28 additions & 0 deletions
28
compute/signed-metadata/src/main/java/com/example/compute/signedmetadata/App.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
// Copyright 2017 Google Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
package com.example.compute.signedmetadata; | ||
|
||
public final class App { | ||
|
||
// AUDIENCE should be set according to your domain and needs. | ||
// Please check https://cloud.google.com/compute/docs/instances/verifying-instance-identity | ||
// for details. | ||
private static final String AUDIENCE = "http://example.com"; | ||
|
||
public static void main(String[] args) { | ||
// We get token from one instance and verify it trusted machine. | ||
String token = new GCPInstance(AUDIENCE).provideToken(); | ||
new VerifyingInstance(AUDIENCE).verifyToken(token); | ||
} | ||
} |
36 changes: 36 additions & 0 deletions
36
compute/signed-metadata/src/main/java/com/example/compute/signedmetadata/GCPInstance.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// Copyright 2017 Google Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
package com.example.compute.signedmetadata; | ||
|
||
import com.example.compute.signedmetadata.token.TokenDownloader; | ||
|
||
import java.io.IOException; | ||
import java.net.URISyntaxException; | ||
|
||
class GCPInstance { | ||
|
||
private String audience; | ||
|
||
GCPInstance(String audience) { | ||
this.audience = audience; | ||
} | ||
|
||
String provideToken() { | ||
try { | ||
return new TokenDownloader().getTokenWithAudience(audience); | ||
} catch (URISyntaxException | IOException e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
} |
65 changes: 65 additions & 0 deletions
65
...e/signed-metadata/src/main/java/com/example/compute/signedmetadata/VerifyingInstance.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
// Copyright 2017 Google Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
package com.example.compute.signedmetadata; | ||
|
||
import com.auth0.jwt.exceptions.AlgorithmMismatchException; | ||
import com.auth0.jwt.exceptions.InvalidClaimException; | ||
import com.auth0.jwt.exceptions.JWTVerificationException; | ||
import com.auth0.jwt.exceptions.SignatureVerificationException; | ||
import com.auth0.jwt.exceptions.TokenExpiredException; | ||
import com.example.compute.signedmetadata.token.DecodedGoogleJWTWrapper; | ||
import com.example.compute.signedmetadata.token.TokenVerifier; | ||
|
||
class VerifyingInstance { | ||
|
||
private String audience; | ||
|
||
VerifyingInstance(String audience) { | ||
this.audience = audience; | ||
} | ||
|
||
void verifyToken(String token) { | ||
TokenVerifier gtv = new TokenVerifier(); | ||
// JWTVerificationException is runtime exception, we don't need to catch it if we want to exit | ||
// process in case of verification problem. However, to handle verification problems | ||
// programmatically we can can JWTVerificationException or specific subclass. | ||
// Following are examples how to handle verification failure. | ||
try { | ||
DecodedGoogleJWTWrapper decodedJWT = gtv.verifyWithAudience(audience, token); | ||
System.out.println("Project id : " + decodedJWT.getProjectId()); | ||
System.out.println("Project number : " + decodedJWT.getProjectNumber()); | ||
// This are examples how to handle exceptions, which indicate verification failure. | ||
} catch (AlgorithmMismatchException e) { | ||
// We assume that downloaded certs are RSA256, this exception will happen if this changes. | ||
throw e; | ||
} catch (SignatureVerificationException e) { | ||
// Could not verify signature of a token, possibly someone provided forged token. | ||
throw e; | ||
} catch (TokenExpiredException e) { | ||
// We encountered old token, possibly replay attack. | ||
throw e; | ||
} catch (InvalidClaimException e) { | ||
// Different Audience for token and for verification, possibly token for other verifier. | ||
throw e; | ||
} catch (JWTVerificationException e) { | ||
// Some other problem during verification | ||
// JWTVerificationException is super-class to: | ||
// - SignatureVerificationException | ||
// - TokenExpiredException | ||
// - InvalidClaimException | ||
throw e; | ||
} | ||
|
||
} | ||
} |
73 changes: 73 additions & 0 deletions
73
...adata/src/main/java/com/example/compute/signedmetadata/token/DecodedGoogleJWTWrapper.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
// Copyright 2017 Google Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
package com.example.compute.signedmetadata.token; | ||
|
||
import com.auth0.jwt.interfaces.DecodedJWT; | ||
import com.google.common.base.Suppliers; | ||
|
||
import java.util.HashMap; | ||
import java.util.Map; | ||
import java.util.Set; | ||
import java.util.function.Supplier; | ||
|
||
public class DecodedGoogleJWTWrapper { | ||
|
||
private static final String KEY_PROJECT_ID = "project_id"; | ||
private static final String KEY_PROJECT_NUMBER = "project_number"; | ||
private static final String GOOGLE_METADATA_SPACE = "google"; | ||
private static final String COMPUTE_ENGINE_METADATA_SUBSPACE = "compute_engine"; | ||
|
||
private DecodedJWT jwt; | ||
private Supplier<Map<String, Object>> computeEngineMetadata = Suppliers.memoize( | ||
() -> { | ||
Map<String, Object> googleMetadata = jwt.getClaims().get(GOOGLE_METADATA_SPACE).asMap(); | ||
Object computeEngineObject = googleMetadata.get(COMPUTE_ENGINE_METADATA_SUBSPACE); | ||
return castToMetadataMap(computeEngineObject); | ||
}); | ||
|
||
DecodedGoogleJWTWrapper(DecodedJWT jwt) { | ||
this.jwt = jwt; | ||
} | ||
|
||
public String getProjectId() { | ||
return getComputeEngineMetadata(KEY_PROJECT_ID); | ||
} | ||
|
||
public String getProjectNumber() { | ||
return getComputeEngineMetadata(KEY_PROJECT_NUMBER); | ||
} | ||
|
||
private String getComputeEngineMetadata(String key) { | ||
return computeEngineMetadata.get().get(key).toString(); | ||
} | ||
|
||
// In Java we can only assure that an object is of class Map, we can check for key and value | ||
// types of an object added to Map, but only if Map is not empty. | ||
@SuppressWarnings({"rawtypes","unchecked"}) | ||
private Map<String, Object> castToMetadataMap(Object object) { | ||
if (object instanceof Map) { | ||
Map map = (Map) object; | ||
if (map.isEmpty()) { | ||
// Map is empty, so we will create new map with desired types | ||
return new HashMap<>(); | ||
} | ||
Set<Map.Entry> set = map.entrySet(); | ||
Map.Entry someEntry = set.iterator().next(); | ||
if (someEntry.getKey() instanceof String) { | ||
return (Map<String, Object>) object; | ||
} | ||
} | ||
throw new RuntimeException("We have not received a map of metadata"); | ||
} | ||
} |
38 changes: 38 additions & 0 deletions
38
...te/signed-metadata/src/main/java/com/example/compute/signedmetadata/token/Downloader.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
// Copyright 2017 Google Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
package com.example.compute.signedmetadata.token; | ||
|
||
import java.io.BufferedReader; | ||
import java.io.InputStreamReader; | ||
import java.io.IOException; | ||
import java.net.URL; | ||
import java.net.URLConnection; | ||
import java.nio.charset.StandardCharsets; | ||
|
||
class Downloader { | ||
|
||
String download(String urlString) throws IOException { | ||
URL url = new URL(urlString); | ||
return download(url.openConnection()); | ||
} | ||
|
||
String download(URLConnection connection) throws IOException { | ||
try(BufferedReader in = new BufferedReader( | ||
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { | ||
StringBuilder sb = new StringBuilder(); | ||
in.lines().forEachOrdered(sb::append); | ||
return sb.toString(); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
very nice - Too few of our samples do this.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks!