From 42afcd10814861622a01a0d2ca653564e16bdc69 Mon Sep 17 00:00:00 2001 From: Thomas Coffee Date: Tue, 13 Jun 2017 17:26:37 -0700 Subject: [PATCH] Discourage use of API key in translation Addresses #1594. --- README.md | 15 +++-- TESTING.md | 8 ++- google-cloud-examples/README.md | 10 +-- .../examples/translate/TranslateExample.java | 6 +- .../snippets/DetectLanguageAndTranslate.java | 5 +- google-cloud-translate/README.md | 7 ++- .../cloud/translate/TranslateOptions.java | 1 + .../testing/RemoteTranslateHelper.java | 61 ++++++++++++++++++- 8 files changed, 87 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 56c1d93cce84..420b00588ea7 100644 --- a/README.md +++ b/README.md @@ -459,7 +459,7 @@ Google Cloud Language (Beta) ### Preview Here is a code snippet showing a simple usage example of LanguageServiceClient. The example assumes that either default application -credentials or a valid api key are available. (See [Authentication section](#authentication) for more information) +credentials or a valid API key are available. (See [Authentication section](#authentication) for more information) ```java try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) { Document document = Document.newBuilder().build(); @@ -476,7 +476,7 @@ Google Cloud Vision (Beta) ### Preview Here is a code snippet showing a simple usage example of ImageAnnotatorClient. -The example assumes that either default application credentials or a valid api key +The example assumes that either default application credentials or a valid API key are available. (See [Authentication section](#authentication) for more information) ```java try (ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create()) { @@ -732,9 +732,8 @@ Google Translation (Beta) Here's a snippet showing a simple usage example. The example shows how to detect the language of some text and how to translate some text. The example assumes that either default application -credentials or a valid api key are available. An api key stored in the `GOOGLE_API_KEY` environment -variable will be automatically detected. Alternatively, you can use the `apiKey(String)` setter in -`TranslateOptions.Builder`. Complete source code can be found at +credentials or a valid API key are available. An API key stored in the `GOOGLE_API_KEY` environment +variable will be automatically detected. Complete source code can be found at [DetectLanguageAndTranslate.java](./google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java). ```java @@ -766,7 +765,7 @@ Google Cloud Speech (Alpha) ### Preview Here is a code snippet showing a simple usage example of SpeechClient. The example assumes that either default application -credentials or a valid api key are available. (See [Authentication section](#authentication) for more information) +credentials or a valid API key are available. (See [Authentication section](#authentication) for more information) Note that you must provide a uri to a FLAC audio file to run this. ```java @@ -796,7 +795,7 @@ Google Cloud Trace (Alpha) ### Preview Here is a code snippet showing a simple usage example of TraceServiceClient. The example assumes that either default application -credentials or a valid api key are available. +credentials or a valid API key are available. Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere. ```java try (TraceServiceClient traceServiceClient = TraceServiceClient.create()) { @@ -814,7 +813,7 @@ Google Cloud Video Intelligence (Alpha) ### Preview Here is a code snippet showing a simple usage example of TraceServiceClient. The example assumes that either default application -credentials or a valid api key are available. +credentials or a valid API key are available. Note that you must [supply credentials](#authentication) and a project ID if running this snippet elsewhere. ```java try (VideoIntelligenceServiceClient videoIntelligenceServiceClient = diff --git a/TESTING.md b/TESTING.md index bb17d20cb25b..2066c8093898 100644 --- a/TESTING.md +++ b/TESTING.md @@ -239,13 +239,14 @@ Google Translation service. 1. Create a test Google Cloud project. -2. Follow [Translate Quickstart](https://cloud.google.com/translate/v2/quickstart) to get an API +2. Download a JSON service account credentials file from the Google Developer's Console. See more about this on the [Google Cloud Platform Authentication page][cloud-platform-authentication] key. 3. Create a `RemoteTranslateHelper` object using your project ID and API key. Here is an example that uses the `RemoteTranslateHelper` to list supported languages. ```java - RemoteTranslateHelper translateHelper = RemoteTranslateHelper.create(PROJECT_ID, API_KEY); + RemoteTranslateHelper translateHelper = + RemoteTranslateHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json")); Translate translate = translateHelper.getOptions().getService(); List languages = translate.listSupportedLanguages(); ``` @@ -258,7 +259,7 @@ Currently, there isn't an emulator for Cloud Spanner, so an alternative is to cr 1. Create a test Google Cloud project. -2. Download a JSON service account credentials file from the Google Developer's Console. See more about this on the [Google Cloud Platform Storage Authentication page][cloud-platform-storage-authentication]. +2. Download a JSON service account credentials file from the Google Developer's Console. See more about this on the [Google Cloud Platform Authentication page][cloud-platform-authentication]. 3. Create or use an existing Cloud Spanner Instance. @@ -283,6 +284,7 @@ Here is an example that uses the `RemoteSpannerHelper` to create a database. RemoteSpannerHelper.cleanUp(); ``` +[cloud-platform-authentication]:https://cloud.google.com/docs/authentication/getting-started [cloud-platform-storage-authentication]:https://cloud.google.com/storage/docs/authentication?hl=en#service_accounts [create-service-account]:https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount [cloud-nio]:https://github.com/GoogleCloudPlatform/google-cloud-java/tree/master/google-cloud-contrib/google-cloud-nio diff --git a/google-cloud-examples/README.md b/google-cloud-examples/README.md index 2da68d386b0d..133aa0f0856c 100644 --- a/google-cloud-examples/README.md +++ b/google-cloud-examples/README.md @@ -160,12 +160,12 @@ To run examples from your command line: * Here's an example run of `TranslateExample`. - Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translation API" is enabled and that you have a valid API key. + Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translation API" is enabled. ``` - target/appassembler/bin/TranslateExample languages - target/appassembler/bin/TranslateExample detect Hello,\ World! - target/appassembler/bin/TranslateExample translate ¡Hola\ Mundo! - target/appassembler/bin/TranslateExample es translate Hello,\ World! + target/appassembler/bin/TranslateExample languages + target/appassembler/bin/TranslateExample detect Hello,\ World! + target/appassembler/bin/TranslateExample translate ¡Hola\ Mundo! + target/appassembler/bin/TranslateExample es translate Hello,\ World! ``` Troubleshooting diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java index 5e3829698177..1172cbb1c727 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java @@ -36,7 +36,7 @@ * * README for compilation instructions. Run this code with *
{@code target/appassembler/bin/TranslateExample
- *  -Dexec.args=" []
+ *  -Dexec.args="[[] ]
  *  list languages ?
  *  detect +
  *  translate +"}
@@ -169,7 +169,7 @@ private static void printUsage() { actionAndParams.append(' ').append(param); } } - System.out.printf("Usage: %s [] [] operation *%s%n", + System.out.printf("Usage: %s [[] ] operation *%s%n", TranslateExample.class.getSimpleName(), actionAndParams); } @@ -189,7 +189,7 @@ public static void main(String... args) throws Exception { optionsBuilder.setTargetLanguage(args[1]); args = Arrays.copyOfRange(args, 3, args.length); } else if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { - optionsBuilder.setApiKey(args[0]); + optionsBuilder.setTargetLanguage(args[0]); actionName = args[1]; args = Arrays.copyOfRange(args, 2, args.length); } else { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java index ab28d630f728..6a65fefa16ef 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java @@ -36,8 +36,9 @@ public class DetectLanguageAndTranslate { public static void main(String... args) { // Create a service object - // Default application credentials or an API key from the GOOGLE_API_KEY environment variable - // are used to authenticate requests + // + // Requests are authenticated using default application credentials if available; otherwise, + // using an API key from the GOOGLE_API_KEY environment variable Translate translate = TranslateOptions.getDefaultInstance().getService(); // Detect the language of some text diff --git a/google-cloud-translate/README.md b/google-cloud-translate/README.md index 7ef10cbdf52d..59d8ee66f732 100644 --- a/google-cloud-translate/README.md +++ b/google-cloud-translate/README.md @@ -42,8 +42,9 @@ Example Application Authentication -------------- -Google Translation requires an API key to be passed with every request. For instructions on how to -get an API key follow the [Translation quickstart](https://cloud.google.com/translate/v2/quickstart). +For instructions on how to set up authentication and make authenticated calls, +follow +the [Translation quickstart](https://cloud.google.com/translate/v2/quickstart). About Google Translation -------------------- @@ -52,7 +53,7 @@ About Google Translation arbitrary string into any supported language. Translation is highly responsive, so websites and applications can integrate with Translation API for fast, dynamic translation of source text from the source language to a target language (e.g., French to English). Language detection is also -available In cases where the source language is unknown. +available in cases where the source language is unknown. See the [Translation quickstart](https://cloud.google.com/translate/v2/quickstart) for more details on how to activate Google Translation for your project. diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java index 15cb7469c427..8adac26c2c23 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java @@ -107,6 +107,7 @@ public Builder setProjectId(String projectId) { * {@code GOOGLE_API_KEY} environment variable. For instructions on how to get an API key see * Translate quickstart. */ + @Deprecated public Builder setApiKey(String apiKey) { this.apiKey = apiKey; return this; diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java index 7fdafdeaa9b8..4970516d3f08 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java @@ -16,11 +16,17 @@ package com.google.cloud.translate.testing; -import com.google.cloud.http.HttpTransportOptions; import com.google.api.gax.retrying.RetrySettings; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.cloud.http.HttpTransportOptions; import com.google.cloud.translate.TranslateOptions; import org.threeten.bp.Duration; +import java.io.IOException; +import java.io.InputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + /** * Utility to create a remote translate configuration for testing. Translate options can be obtained * via the {@link #getOptions()} ()} method. Returned options have custom @@ -34,6 +40,7 @@ * both set to {@code 60000}. */ public class RemoteTranslateHelper { + private static final Logger logger = Logger.getLogger(RemoteTranslateHelper.class.getName()); private final TranslateOptions options; @@ -49,11 +56,43 @@ public TranslateOptions getOptions() { return options; } + /** + * Creates a {@code RemoteTranslateHelper} object for the given project id and JSON key input + * stream. + * + * @param projectId id of the project to be used for running the tests + * @param keyStream input stream for a JSON key + * @return A {@code RemoteTranslateHelper} object for the provided options + * @throws com.google.cloud.translate.testing.RemoteTranslateHelper.TranslateHelperException if + * {@code keyStream} is not a valid JSON key stream + */ + public static RemoteTranslateHelper create(String projectId, InputStream keyStream) + throws TranslateHelperException { + try { + HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions(); + transportOptions = transportOptions.toBuilder().setConnectTimeout(60000).setReadTimeout(60000) + .build(); + TranslateOptions translateOptions = TranslateOptions.newBuilder() + .setCredentials(GoogleCredentials.fromStream(keyStream)) + .setProjectId(projectId) + .setRetrySettings(retryParams()) + .setTransportOptions(transportOptions) + .build(); + return new RemoteTranslateHelper(translateOptions); + } catch (IOException ex) { + if (logger.isLoggable(Level.WARNING)) { + logger.log(Level.WARNING, ex.getMessage()); + } + throw TranslateHelperException.translate(ex); + } + } + /** * Creates a {@code RemoteTranslateHelper} object for the given API key. * * @param apiKey API key used to issue requests to Google Translation. */ + @Deprecated public static RemoteTranslateHelper create(String apiKey) { HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions(); transportOptions = transportOptions.toBuilder().setConnectTimeout(60000).setReadTimeout(60000) @@ -67,7 +106,8 @@ public static RemoteTranslateHelper create(String apiKey) { } /** - * Creates a {@code RemoteStorageHelper} object. + * Creates a {@code RemoteTranslateHelper} object using default project id and authentication + * credentials. */ public static RemoteTranslateHelper create() { HttpTransportOptions transportOptions = TranslateOptions.getDefaultHttpTransportOptions(); @@ -91,4 +131,21 @@ private static RetrySettings retryParams() { .setMaxRpcTimeout(Duration.ofMillis(120000L)) .build(); } + + public static class TranslateHelperException extends RuntimeException { + + private static final long serialVersionUID = -1356870058436149798L; + + public TranslateHelperException(String message) { + super(message); + } + + public TranslateHelperException(String message, Throwable cause) { + super(message, cause); + } + + public static TranslateHelperException translate(Exception ex) { + return new TranslateHelperException(ex.getMessage(), ex); + } + } }