-
Notifications
You must be signed in to change notification settings - Fork 878
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
Api change #2888
Merged
Merged
Api change #2888
Changes from 25 commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
4ddb74e
token authorization update
1304ca3
update token
fde5f4d
token authorization plugin test
8ec3c40
fix format
d50beae
add key file generation at default
udaij12 d5c25e6
fix format
udaij12 1b35372
Merge branch 'master' into api_change
# Please enter a commit message…
0010c86
Merge branch 'master' into api_change
udaij12 62cadc8
updated token plugin
udaij12 51f5889
Merge branch 'api_change' of https://github.com/pytorch/serve into ap…
udaij12 129b652
fixed file delete
udaij12 cecc086
fixed imports
udaij12 6876781
added custom expection
udaij12 4848114
fix format
udaij12 fa32c28
token handler
udaij12 c5c0f77
fix doc
udaij12 84343c4
merging master
udaij12 3b7fe29
fixed handler
udaij12 0d7afe3
added integration tests
udaij12 13caa27
Added integration tests
udaij12 a49acf5
updating token auth
udaij12 6b329b2
small changes to token auth
udaij12 0690e01
fixing changes
udaij12 eb37eff
changed keyfile to dictionary and updated readme and tests
udaij12 71bc7f5
remove comments
udaij12 3e18230
changes to tests
udaij12 f69c632
added config file
udaij12 599c635
Merge branch 'master' into api_change
mreso 55cedd5
reduce time for expiration test
udaij12 4c7080d
Merge branch 'api_change' of https://github.com/pytorch/serve into ap…
udaij12 54841d9
change test to mnist
udaij12 4e1c1ea
removing install from src
udaij12 698b95a
final test change
udaij12 68b3b04
Fix spellcheck
mreso 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
# TorchServe token authorization API | ||
|
||
## Configuration | ||
1. Enable token authorization by adding the provided plugin at start using the `--plugin-path` command. | ||
2. Torchserve will enable token authorization if the plugin is provided. In the current working directory a file `key_file.json` will be generated. | ||
1. Example key file: | ||
|
||
```python | ||
[ | ||
{ | ||
"Management Key": "I_J_ItMb", | ||
"ExpirationTime": "2024-02-16T01:27:56.749292Z" | ||
}, | ||
{ | ||
"Inference Key": "FINhR1fj", | ||
"ExpirationTime": "2024-02-16T01:27:56.749273Z" | ||
}, | ||
{ | ||
"API Key": "m4M-5IBY" | ||
} | ||
] | ||
``` | ||
|
||
3. There are 3 keys and each have a different use. | ||
1. Management key: Used for management APIs. Example: | ||
`curl http://localhost:8081/models/densenet161 -H "Authorization: Bearer I_J_ItMb"` | ||
2. Inference key: Used for inference APIs. Example: | ||
`curl http://127.0.0.1:8080/predictions/densenet161 -T examples/image_classifier/kitten.jpg -H "Authorization: Bearer FINhR1fj"` | ||
3. API key: Used for the token authorization API. Check section 4 for API use. | ||
4. The plugin also includes an API in order to generate a new key to replace either the management or inference key. | ||
1. Management Example: | ||
`curl localhost:8081/token?type=management -H "Authorization: Bearer m4M-5IBY"` will replace the current management key in the key_file with a new one and will update the expiration time. | ||
2. Inference example: | ||
`curl localhost:8081/token?type=inference -H "Authorization: Bearer m4M-5IBY"` | ||
|
||
Users will have to use either one of the APIs above. | ||
|
||
5. When users shut down the server the key_file will be deleted. | ||
|
||
|
||
## Customization | ||
Torchserve offers various ways to customize the token authorization to allow owners to reach the desired result. | ||
1. Time to expiration is set to default at 60 minutes but can be changed in the config.properties by adding `token_expiration_min`. Ex:`token_expiration_min=30` | ||
2. The token authorization code is consolidated in the plugin and thus can be changed without impacting the frontend or end result. The only thing the user cannot change is: | ||
1. The urlPattern for the plugin must be 'token' and the class name must not change | ||
2. The `generateKeyFile`, `checkTokenAuthorization`, and `setTime` functions return type and signature must not change. However, the code in the functions can be modified depending on user necessity. | ||
|
||
## Notes | ||
1. DO NOT MODIFY THE KEY FILE. Modifying the key file might impact reading and writing to the file thus preventing new keys from properly being displayed in the file. | ||
2. 3 tokens allow the owner with the most flexibility in use and enables them to adapt the tokens to their use. Owners of the server can provide users with the inference token if users should not mess with models. The owner can also provide owners with the management key if owners want users to add and remove models. |
32 changes: 32 additions & 0 deletions
32
frontend/archive/src/main/java/org/pytorch/serve/archive/model/InvalidKeyException.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,32 @@ | ||
package org.pytorch.serve.archive.model; | ||
|
||
public class InvalidKeyException extends ModelException { | ||
|
||
private static final long serialVersionUID = 1L; | ||
|
||
/** | ||
* Constructs an {@code InvalidKeyException} with the specified detail message. | ||
* | ||
* @param message The detail message (which is saved for later retrieval by the {@link | ||
* #getMessage()} method) | ||
*/ | ||
public InvalidKeyException(String message) { | ||
super(message); | ||
} | ||
|
||
/** | ||
* Constructs an {@code InvalidKeyException} with the specified detail message and cause. | ||
* | ||
* <p>Note that the detail message associated with {@code cause} is <i>not</i> automatically | ||
* incorporated into this exception's detail message. | ||
* | ||
* @param message The detail message (which is saved for later retrieval by the {@link | ||
* #getMessage()} method) | ||
* @param cause The cause (which is saved for later retrieval by the {@link #getCause()} | ||
* method). (A null value is permitted, and indicates that the cause is nonexistent or | ||
* unknown.) | ||
*/ | ||
public InvalidKeyException(String message, Throwable cause) { | ||
super(message, cause); | ||
} | ||
} |
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
103 changes: 103 additions & 0 deletions
103
frontend/server/src/main/java/org/pytorch/serve/http/TokenAuthorizationHandler.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,103 @@ | ||
package org.pytorch.serve.http; | ||
|
||
import io.netty.channel.ChannelHandlerContext; | ||
import io.netty.handler.codec.http.FullHttpRequest; | ||
import io.netty.handler.codec.http.QueryStringDecoder; | ||
import java.lang.reflect.*; | ||
import org.pytorch.serve.archive.DownloadArchiveException; | ||
import org.pytorch.serve.archive.model.InvalidKeyException; | ||
import org.pytorch.serve.archive.model.ModelException; | ||
import org.pytorch.serve.archive.workflow.WorkflowException; | ||
import org.pytorch.serve.util.ConfigManager; | ||
import org.pytorch.serve.util.TokenType; | ||
import org.pytorch.serve.wlm.WorkerInitializationException; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
/** | ||
* A class handling token check for all inbound HTTP requests | ||
* | ||
* <p>This class // | ||
*/ | ||
public class TokenAuthorizationHandler extends HttpRequestHandlerChain { | ||
|
||
private static final Logger logger = LoggerFactory.getLogger(TokenAuthorizationHandler.class); | ||
private static TokenType tokenType; | ||
private static Boolean tokenEnabled = false; | ||
private static Class<?> tokenClass; | ||
private static Object tokenObject; | ||
private static Integer timeToExpirationMinutes = 60; | ||
|
||
/** Creates a new {@code InferenceRequestHandler} instance. */ | ||
public TokenAuthorizationHandler(TokenType type) { | ||
tokenType = type; | ||
} | ||
|
||
@Override | ||
public void handleRequest( | ||
ChannelHandlerContext ctx, | ||
FullHttpRequest req, | ||
QueryStringDecoder decoder, | ||
String[] segments) | ||
throws ModelException, DownloadArchiveException, WorkflowException, | ||
WorkerInitializationException { | ||
if (tokenEnabled) { | ||
if (tokenType == TokenType.MANAGEMENT) { | ||
if (req.toString().contains("/token")) { | ||
checkTokenAuthorization(req, "token"); | ||
} else { | ||
checkTokenAuthorization(req, "management"); | ||
} | ||
} else if (tokenType == TokenType.INFERENCE) { | ||
checkTokenAuthorization(req, "inference"); | ||
} | ||
} | ||
chain.handleRequest(ctx, req, decoder, segments); | ||
} | ||
|
||
public static void setupTokenClass() { | ||
try { | ||
tokenClass = Class.forName("org.pytorch.serve.plugins.endpoint.Token"); | ||
tokenObject = tokenClass.getDeclaredConstructor().newInstance(); | ||
Method method = tokenClass.getMethod("setTime", Integer.class); | ||
Integer time = ConfigManager.getInstance().getTimeToExpiration(); | ||
if (time != 0) { | ||
timeToExpirationMinutes = time; | ||
} | ||
method.invoke(tokenObject, timeToExpirationMinutes); | ||
method = tokenClass.getMethod("generateKeyFile", String.class); | ||
if ((boolean) method.invoke(tokenObject, "token")) { | ||
logger.info("TOKEN CLASS IMPORTED SUCCESSFULLY"); | ||
} | ||
} catch (NoSuchMethodException | ||
| IllegalAccessException | ||
| InstantiationException | ||
| InvocationTargetException | ||
| ClassNotFoundException e) { | ||
e.printStackTrace(); | ||
logger.error("TOKEN CLASS IMPORTED UNSUCCESSFULLY"); | ||
throw new IllegalStateException("Unable to import token class", e); | ||
} | ||
tokenEnabled = true; | ||
} | ||
|
||
private void checkTokenAuthorization(FullHttpRequest req, String type) throws ModelException { | ||
|
||
try { | ||
Method method = | ||
tokenClass.getMethod( | ||
"checkTokenAuthorization", | ||
io.netty.handler.codec.http.FullHttpRequest.class, | ||
String.class); | ||
boolean result = (boolean) (method.invoke(tokenObject, req, type)); | ||
if (!result) { | ||
throw new InvalidKeyException( | ||
"Token Authentication failed. Token either incorrect, expired, or not provided correctly"); | ||
} | ||
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { | ||
e.printStackTrace(); | ||
throw new InvalidKeyException( | ||
"Token Authentication failed. Token either incorrect, expired, or not provided correctly"); | ||
} | ||
} | ||
} |
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
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
7 changes: 7 additions & 0 deletions
7
frontend/server/src/main/java/org/pytorch/serve/util/TokenType.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,7 @@ | ||
package org.pytorch.serve.util; | ||
|
||
public enum TokenType { | ||
INFERENCE, | ||
MANAGEMENT, | ||
TOKEN_API | ||
} |
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
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
Oops, something went wrong.
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.
I would prefer a dict instead of a list as the main structure. Otherwise you have to look into the object to see what key you have. (see test where you check if "managemen_key in iterm" etc). Why not {"management": {"key":"..."} etc}? In that case you can easily access the values with