Skip to content

Commit

Permalink
Add signed-metadata example (#828)
Browse files Browse the repository at this point in the history
  • Loading branch information
jprzychodzen authored and lesv committed Aug 28, 2017
1 parent 3096f5a commit 509d5e4
Show file tree
Hide file tree
Showing 11 changed files with 544 additions and 0 deletions.
1 change: 1 addition & 0 deletions compute/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
<module>error-reporting</module>
<module>mailjet</module>
<module>sendgrid</module>
<module>signed-metadata</module>
</modules>

</project>
39 changes: 39 additions & 0 deletions compute/signed-metadata/README.md
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`
87 changes: 87 additions & 0 deletions compute/signed-metadata/pom.xml
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>
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);
}
}
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);
}
}
}
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;
}

}
}
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");
}
}
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();
}
}
}
Loading

0 comments on commit 509d5e4

Please sign in to comment.