-
Notifications
You must be signed in to change notification settings - Fork 2.9k
GCF: Add Slack sample + clean up imports #2394
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
Merged
Changes from 1 commit
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
1113978
Add Slack sample + clean up imports
b84f11b
Address comments
2827496
Remove excess gcloudignore + actually disable tests
7638e6c
Merge branch 'master' into gcf-slack
6383b60
Simplify tests + run them on Kokoro. ALSO bugfix unused shellchecks.
0c2d0ff
Remove extra file
032e107
HACK: resolve surefire issue via file presence
38a32f1
HACK take 2: use a different filepath
5005a1b
HACK take 3: use env var not used by local Cloud Build
1fc4182
Merge branch 'master' into gcf-slack
1583f63
Remove gitignore now that config.json isnt used
d64f80d
Merge branch 'master' into gcf-slack
5ee5f0d
DBG: print defined env vars
3dc4128
DBG take 2
d3be1ce
DBG take 3
4b6ea96
DBG take 4
c6d877a
DBG take 5
3fcc16e
DBG take 6
7841758
DBG take 7
561fb11
Fix tests...?
18b011e
Revert dbg commits + fix tests
f336ae5
Merge branch 'master' into gcf-slack
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 hidden or 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 @@ | ||
| config.json |
This file contains hidden or 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,4 @@ | ||
| { | ||
| "SLACK_SECRET": "[YOUR_SLACK_SIGNING_SECRET]", | ||
| "KG_API_KEY": "[YOUR_KG_API_KEY]" | ||
| } | ||
This file contains hidden or 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
172 changes: 172 additions & 0 deletions
172
functions/snippets/src/main/java/com/example/functions/SlackSlashCommand.java
This file contains hidden or 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,172 @@ | ||
| /* | ||
| * Copyright 2020 Google LLC | ||
| * | ||
| * 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. | ||
| */ | ||
|
|
||
| package com.example.functions; | ||
|
|
||
| import com.github.seratch.jslack.app_backend.SlackSignature; | ||
| import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; | ||
| import com.google.api.client.json.jackson2.JacksonFactory; | ||
| import com.google.api.client.util.ArrayMap; | ||
| import com.google.api.services.kgsearch.v1.Kgsearch; | ||
| import com.google.cloud.functions.HttpFunction; | ||
| import com.google.cloud.functions.HttpRequest; | ||
| import com.google.cloud.functions.HttpResponse; | ||
| import com.google.gson.Gson; | ||
| import com.google.gson.JsonArray; | ||
| import com.google.gson.JsonObject; | ||
| import java.io.BufferedWriter; | ||
| import java.io.IOException; | ||
| import java.net.HttpURLConnection; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.security.GeneralSecurityException; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import java.util.logging.Logger; | ||
| import java.util.stream.Collectors; | ||
|
|
||
| public class SlackSlashCommand implements HttpFunction { | ||
|
|
||
| private Kgsearch kgClient; | ||
| private static String API_KEY; | ||
| private static String SLACK_SECRET; | ||
| private static final Logger LOGGER = Logger.getLogger(HelloHttp.class.getName()); | ||
| private SlackSignature.Verifier verifier; | ||
| private Gson gson = new Gson(); | ||
|
|
||
| public SlackSlashCommand() throws IOException, GeneralSecurityException { | ||
| kgClient = new Kgsearch.Builder( | ||
| GoogleNetHttpTransport.newTrustedTransport(), new JacksonFactory(), null).build(); | ||
|
|
||
| // Read + parse config file | ||
| Path configPath = Path.of(System.getProperty("user.dir"), "config.json"); | ||
ace-n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| JsonObject configJson = (new Gson()).fromJson(Files.readString(configPath), JsonObject.class); | ||
|
|
||
| SLACK_SECRET = configJson.get("SLACK_SECRET").getAsString(); | ||
| API_KEY = configJson.get("KG_API_KEY").getAsString(); | ||
|
|
||
| verifier = new SlackSignature.Verifier(new SlackSignature.Generator(SLACK_SECRET)); | ||
| } | ||
|
|
||
| private boolean isValidSlackWebhook(HttpRequest request, String requestBody) throws IOException { | ||
ace-n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Check for headers | ||
| HashMap<String, List<String>> headers = new HashMap(request.getHeaders()); | ||
| if (!headers.containsKey("X-Slack-Request-Timestamp") | ||
| || !headers.containsKey("X-Slack-Signature")) { | ||
| return false; | ||
| } | ||
|
|
||
| return verifier.isValid( | ||
| headers.get("X-Slack-Request-Timestamp").get(0), | ||
| requestBody, | ||
| headers.get("X-Slack-Signature").get(0), | ||
| 1L); | ||
| } | ||
|
|
||
| private void addPropertyIfPresent( | ||
| JsonObject target, String targetName, ArrayMap source, String sourceName) { | ||
| if (source.containsKey(sourceName)) { | ||
| target.addProperty(targetName, source.get(sourceName).toString()); | ||
| } | ||
| } | ||
|
|
||
| private String formatSlackMessage(List<Object> kgResults, String query) { | ||
ace-n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| JsonObject attachmentJson = new JsonObject(); | ||
| JsonArray attachments = new JsonArray(); | ||
|
|
||
| JsonObject responseJson = new JsonObject(); | ||
| responseJson.addProperty("response_type", "in_channel"); | ||
| responseJson.addProperty("text", String.format("Query: %s", query)); | ||
|
|
||
| // Extract the first entity from the result list, if any | ||
| if (kgResults.size() == 0) { | ||
| attachmentJson.addProperty("text","No results match your query..."); | ||
|
|
||
| attachments.add(attachmentJson); | ||
| responseJson.add("attachments", attachmentJson); | ||
|
|
||
| return gson.toJson(responseJson); | ||
| } | ||
|
|
||
| ArrayMap entity = (ArrayMap) ((ArrayMap) kgResults.get(0)).get("result"); | ||
ace-n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Construct Knowledge Graph response attachment | ||
| String title = entity.get("name").toString(); | ||
| if (entity.containsKey("description")) { | ||
| title = String.format("%s: %s", title, entity.get("description").toString()); | ||
| } | ||
ace-n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| attachmentJson.addProperty("title", title); | ||
|
|
||
| if (entity.containsKey("detailedDescription")) { | ||
| ArrayMap detailedDescJson = (ArrayMap) entity.get("detailedDescription"); | ||
| addPropertyIfPresent(attachmentJson, "title_link", detailedDescJson, "url"); | ||
| addPropertyIfPresent(attachmentJson, "text", detailedDescJson, "articleBody"); | ||
| } | ||
|
|
||
| if (entity.containsKey("image")) { | ||
| ArrayMap imageJson = (ArrayMap) entity.get("image"); | ||
| addPropertyIfPresent(attachmentJson, "image_url", imageJson, "contentUrl"); | ||
| } | ||
|
|
||
| // Construct top level response | ||
| attachments.add(attachmentJson); | ||
| responseJson.add("attachments", attachmentJson); | ||
|
|
||
| return gson.toJson(responseJson); | ||
| } | ||
|
|
||
| private List<Object> searchKnowledgeGraph(String query) throws IOException { | ||
ace-n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| Kgsearch.Entities.Search kgRequest = kgClient.entities().search(); | ||
| kgRequest.setQuery(query); | ||
| kgRequest.setKey(API_KEY); | ||
|
|
||
| return kgRequest.execute().getItemListElement(); | ||
| } | ||
|
|
||
| @Override | ||
| public void service(HttpRequest request, HttpResponse response) throws IOException { | ||
|
|
||
| // Validate request | ||
| if (request.getMethod() != "POST") { | ||
| response.setStatusCode(HttpURLConnection.HTTP_BAD_METHOD); | ||
| return; | ||
| } | ||
|
|
||
| // reader can only be read once per request, so we preserve its contents | ||
| String bodyString = request.getReader().lines().collect(Collectors.joining()); | ||
| JsonObject body = (new Gson()).fromJson(bodyString, JsonObject.class); | ||
|
|
||
| if (body == null || !body.has("text")) { | ||
| response.setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); | ||
| return; | ||
| } | ||
|
|
||
| if (!isValidSlackWebhook(request, bodyString)) { | ||
| response.setStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED); | ||
| return; | ||
| } | ||
|
|
||
| String query = body.get("text").getAsString(); | ||
|
|
||
| // Call knowledge graph API | ||
| List<Object> kgResults = searchKnowledgeGraph(query); | ||
ace-n marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| // Format response to Slack | ||
| BufferedWriter writer = response.getWriter(); | ||
| writer.write(formatSlackMessage(kgResults, query)); | ||
| } | ||
| } | ||
172 changes: 172 additions & 0 deletions
172
functions/snippets/src/test/java/com/example/functions/SlackSlashCommandTest.java
This file contains hidden or 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,172 @@ | ||
| /* | ||
| * Copyright 2020 Google LLC | ||
| * | ||
| * 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. | ||
| */ | ||
|
|
||
| package com.example.functions; | ||
|
|
||
| import static com.google.common.truth.Truth.assertThat; | ||
| import static org.mockito.Mockito.times; | ||
| import static org.mockito.Mockito.verify; | ||
| import static org.powermock.api.mockito.PowerMockito.mock; | ||
| import static org.powermock.api.mockito.PowerMockito.when; | ||
|
|
||
| import com.github.seratch.jslack.app_backend.SlackSignature; | ||
| import com.google.api.client.googleapis.json.GoogleJsonResponseException; | ||
| import com.google.cloud.functions.HttpRequest; | ||
| import com.google.cloud.functions.HttpResponse; | ||
| import java.io.BufferedReader; | ||
| import java.io.BufferedWriter; | ||
| import java.io.IOException; | ||
| import java.io.StringReader; | ||
| import java.io.StringWriter; | ||
| import java.net.HttpURLConnection; | ||
| import java.security.GeneralSecurityException; | ||
| import java.time.ZoneOffset; | ||
| import java.time.ZonedDateTime; | ||
| import java.util.Arrays; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import org.junit.Before; | ||
| import org.junit.Test; | ||
| import org.mockito.ArgumentMatchers; | ||
| import org.mockito.Mock; | ||
| import org.powermock.reflect.Whitebox; | ||
|
|
||
| public class SlackSlashCommandTest { | ||
|
|
||
| private BufferedWriter writerOut; | ||
| private StringWriter responseOut; | ||
|
|
||
| @Mock private HttpRequest request; | ||
| @Mock private HttpResponse response; | ||
|
|
||
| @Mock private SlackSignature.Verifier alwaysValidVerifier; | ||
|
|
||
| @Before | ||
| public void beforeTest() throws IOException { | ||
| request = mock(HttpRequest.class); | ||
| when(request.getReader()).thenReturn(new BufferedReader(new StringReader(""))); | ||
|
|
||
| response = mock(HttpResponse.class); | ||
|
|
||
| responseOut = new StringWriter(); | ||
|
|
||
| writerOut = new BufferedWriter(responseOut); | ||
| when(response.getWriter()).thenReturn(writerOut); | ||
|
|
||
| alwaysValidVerifier = mock(SlackSignature.Verifier.class); | ||
| when(alwaysValidVerifier.isValid( | ||
| ArgumentMatchers.any(), | ||
| ArgumentMatchers.any(), | ||
| ArgumentMatchers.any(), | ||
| ArgumentMatchers.anyLong()) | ||
| ).thenReturn(true); | ||
|
|
||
| // Construct valid header list | ||
| HashMap<String, List<String>> validHeaders = new HashMap<String, List<String>>(); | ||
| String validSlackSignature = System.getenv("SLACK_TEST_SIGNATURE"); | ||
| String timestamp = | ||
| Long.toString(ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC) | ||
| .toInstant().toEpochMilli()); | ||
|
|
||
| validHeaders.put("X-Slack-Signature", Arrays.asList(validSlackSignature)); | ||
| validHeaders.put("X-Slack-Request-Timestamp", Arrays.asList(timestamp)); | ||
|
|
||
| when(request.getHeaders()).thenReturn(validHeaders); | ||
| } | ||
|
|
||
| @Test | ||
| public void onlyAcceptsPostRequestsTest() throws IOException, GeneralSecurityException { | ||
| when(request.getMethod()).thenReturn("GET"); | ||
| new SlackSlashCommand().service(request, response); | ||
|
|
||
| writerOut.flush(); | ||
| verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_BAD_METHOD); | ||
| } | ||
|
|
||
| @Test | ||
| public void requiresSlackAuthHeadersTest() throws IOException, GeneralSecurityException { | ||
| StringReader requestReadable = new StringReader("{ \"text\": \"foo\" }\n"); | ||
|
|
||
| when(request.getMethod()).thenReturn("POST"); | ||
| when(request.getReader()).thenReturn(new BufferedReader(requestReadable)); | ||
|
|
||
| new SlackSlashCommand().service(request, response); | ||
|
|
||
| // Do NOT look for HTTP_BAD_REQUEST here (that means the request WAS authorized)! | ||
| verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_UNAUTHORIZED); | ||
| } | ||
|
|
||
| @Test | ||
| public void recognizesValidSlackTokenTest() throws IOException, GeneralSecurityException { | ||
| StringReader requestReadable = new StringReader("{}"); | ||
|
|
||
| when(request.getReader()).thenReturn(new BufferedReader(requestReadable)); | ||
| when(request.getMethod()).thenReturn("POST"); | ||
|
|
||
| new SlackSlashCommand().service(request, response); | ||
|
|
||
| verify(response, times(1)).setStatusCode(HttpURLConnection.HTTP_BAD_REQUEST); | ||
| } | ||
|
|
||
| @Test(expected = GoogleJsonResponseException.class) | ||
| public void handlesSearchErrorTest() throws IOException, GeneralSecurityException { | ||
| StringReader requestReadable = new StringReader("{ \"text\": \"foo\" }\n"); | ||
|
|
||
| when(request.getReader()).thenReturn(new BufferedReader(requestReadable)); | ||
| when(request.getMethod()).thenReturn("POST"); | ||
|
|
||
| SlackSlashCommand functionInstance = new SlackSlashCommand(); | ||
| Whitebox.setInternalState(functionInstance, "verifier", alwaysValidVerifier); | ||
| Whitebox.setInternalState(SlackSlashCommand.class, "API_KEY", "gibberish"); | ||
|
|
||
| // Should throw a GoogleJsonResponseException (due to invalid API key) | ||
| functionInstance.service(request, response); | ||
| } | ||
|
|
||
| @Test | ||
| public void handlesEmptyKgResultsTest() throws IOException, GeneralSecurityException { | ||
| StringReader requestReadable = new StringReader("{ \"text\": \"asdfjkl13579\" }\n"); | ||
|
|
||
| when(request.getReader()).thenReturn(new BufferedReader(requestReadable)); | ||
| when(request.getMethod()).thenReturn("POST"); | ||
|
|
||
| SlackSlashCommand functionInstance = new SlackSlashCommand(); | ||
| Whitebox.setInternalState(functionInstance, "verifier", alwaysValidVerifier); | ||
|
|
||
|
|
||
| functionInstance.service(request, response); | ||
|
|
||
| writerOut.flush(); | ||
| assertThat(responseOut.toString()).contains("No results match your query..."); | ||
| } | ||
|
|
||
| @Test | ||
| public void handlesPopulatedKgResultsTest() throws IOException, GeneralSecurityException { | ||
| StringReader requestReadable = new StringReader("{ \"text\": \"lion\" }\n"); | ||
|
|
||
| when(request.getReader()).thenReturn(new BufferedReader(requestReadable)); | ||
| when(request.getMethod()).thenReturn("POST"); | ||
|
|
||
| SlackSlashCommand functionInstance = new SlackSlashCommand(); | ||
| Whitebox.setInternalState(functionInstance, "verifier", alwaysValidVerifier); | ||
|
|
||
|
|
||
| functionInstance.service(request, response); | ||
|
|
||
| writerOut.flush(); | ||
| assertThat(responseOut.toString()).contains("https://en.wikipedia.org/wiki/Lion"); | ||
| } | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.