This repository has been archived by the owner on Nov 19, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 136
/
TwilioCapability.cls
310 lines (272 loc) · 10.8 KB
/
TwilioCapability.cls
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
Copyright (c) 2012 Twilio, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Generates capability tokens that authorize Twilio Client running in
* the user's browser or mobile device to contact Twilio directly to
* make outgoing calls or receive incoming calls.
*/
global class TwilioCapability {
private class IllegalStateException extends Exception {}
private String accountSid;
private String authToken;
private List<String> scopes;
// Incoming Parameter holding until generate token time
private boolean buildIncomingScope = false;
private String incomingClientName = null;
// Outgoing Paramater holding until generate token time
private boolean buildOutgoingScope = false;
private String appSid = null;
private Map<String, String> outgoingParams = null;
/**
* Create a new TwilioCapability with zero permissions. Next steps are to
* grant access to resources by configuring this token through the functions
* allowXXXX.
*
* @param accountSid the account sid to which this token is granted access
* @param authToken the secret key used to sign the token. Note, this auth token is not visible to the user of the token.
*/
global TwilioCapability(String accountSid, String authToken) {
this.accountSid = accountSid;
this.authToken = authToken;
this.scopes = new List<String>();
}
/**
* Allow the user of this token to make outgoing connections.
*
* @param applicationSid
* the application to which this token grants access
*/
global void allowClientOutgoing(String appSid) {
allowClientOutgoing(appSid, null);
}
/**
* Allow the user of this token to make outgoing connections.
*
* @param applicationSid
* the application to which this token grants access
* @param params
* signed parameters that the user of this token cannot
* overwrite.
*/
global void allowClientOutgoing(String appSid, Map<String, String> params) {
this.buildOutgoingScope = true;
this.outgoingParams = params;
this.appSid = appSid;
}
/**
* If the user of this token should be allowed to accept incoming
* connections then configure the TwilioCapability through this method and
* specify the client name.
*
* @param clientName
*/
global void allowClientIncoming(String clientName) {
// Save the default client name
this.incomingClientName = clientName;
this.buildIncomingScope = true;
}
/**
* Allow the user of this token to access their event stream.
*
* @param filters
* key/value filters to apply to the event stream
*/
global void allowEventStream(Map<String, String> filters) {
Map<String, String> value = new Map<String, String>();
value.put('path', '/2010-04-01/Events');
if (filters != null) {
value.put('params', generateParamString(filters));
}
this.scopes.add(buildScopeString('stream', 'subscribe', value));
}
/**
* Generates a new token based on the credentials and permissions that
* previously has been granted to this token.
*
* @return the newly generated token that is valid for 3600 seconds
*/
global String generateToken() {
return generateToken(3600);
}
/**
* Generates a new token based on the credentials and permissions that
* previously has been granted to this token.
*
* @param expiresAt
* the expiration instance of the token.
* @return the newly generated token that is valid for ttl seconds
*/
global String generateToken(long ttl) {
// Build these scopes lazily when we generate tokens so we know
// if we have a default or incoming client name to use
buildIncomingScope();
buildOutgoingScope();
Map<String, Object> payload = new Map<String, Object>();
payload.put('iss', this.accountSid);
payload.put('exp', String.valueOf(System.currentTimeMillis()/1000 + ttl));
payload.put('scope', join(this.scopes, ' '));
return jwtEncode(payload, this.authToken);
}
/* PRIVATE METHODS */
/**
* Construct the scope string for outgoing calls
*/
private void buildOutgoingScope() {
if (this.buildOutgoingScope) {
Map<String, String> values = new Map<String, String> { 'appSid' => appSid };
if (this.incomingClientName != null) {
values.put('clientName', this.incomingClientName);
}
// Build outgoing scopes
if (this.outgoingParams != null && !this.outgoingParams.isEmpty()) {
values.put('appParams', generateParamString(this.outgoingParams));
}
this.scopes.add(buildScopeString('client', 'outgoing', values));
}
}
/**
* Construct the scope string for incoming calls
*/
private void buildIncomingScope() {
if (this.buildIncomingScope) {
Map<String, String> value = new Map<String, String>();
// Incoming name, which takes precedence over the default client name.
// However, we do NOT accept a null clientName here.
if (this.incomingClientName != null) {
value.put('clientName', this.incomingClientName);
} else {
throw new IllegalStateException('No client name set');
}
this.scopes.add(buildScopeString('client', 'incoming', value));
}
}
/**
* Construct JWT scope string in the format "scope:<service>:<privilege>?<params>"
*/
private static String buildScopeString(String service, String privilege,
Map<String, String> params) {
String scope = 'scope:'+service+':'+privilege;
if (params!=null && !params.isEmpty()) {
scope += '?'+generateParamString(params);
}
return scope;
}
/**
* Construct URL-style query param string, e.g. key1=val1&key2=val2&...keyN=valN
*/
@TestVisible
private static String generateParamString(Map<String, String> params) {
String queryString = '';
Set<String> keySet = params.keySet();
for (String key : keySet) {
if (queryString.length() > 0) {
queryString += '&';
}
queryString += EncodingUtil.urlEncode(key, 'UTF-8') + '='
+ EncodingUtil.urlEncode(params.get(key), 'UTF-8');
}
return queryString;
}
/**
* Construct JWT token consisting of header, payload, and signature
*
* See http://self-issued.info/docs/draft-jones-json-web-token.html
*/
@TestVisible
private static String jwtEncode(Map<String, Object> payload, String key) {
Map<String, Object> header = new Map<String, Object>();
header.put('typ', 'JWT');
header.put('alg', 'HS256');
List<String> segments = new List<String>();
segments.add(urlSafeEncodeBase64(JSON.serialize(header)));
segments.add(urlSafeEncodeBase64(JSON.serialize(payload)));
String signature = sign(join(segments, '.'), key);
segments.add(signature);
return join(segments, '.');
}
@TestVisible
private static String urlSafeEncodeBase64(String data) {
return urlSafeEncodeBase64(Blob.valueOf(data));
}
@TestVisible
private static String urlSafeEncodeBase64(Blob data) {
String encodedString = EncodingUtil.base64Encode(data);
return encodedString.replace('+','-').replace('/','_').replace('=', ''); // make URL-safe
}
/**
* Construct a String containing the contents of 'vals' separated by 'sep'
*/
@TestVisible
private static String join(List<String> vals, String sep) {
String sb = '';
for (Iterator<String> it=vals.iterator(); it.hasNext(); ) {
String value = it.next();
if (sb.length() != 0)
sb += sep;
sb += value;
}
return sb;
}
/**
* Generate a signature for the token
*
* See http://self-issued.info/docs/draft-jones-json-web-signature.html
* and http://discussion.forum.nokia.com/forum/showthread.php?130974-Help-required-How-to-generate-a-MAC-(HMAC-SHA1)-with-Java
*/
private static String sign(String data, String key) {
Blob mac = Crypto.generateMac('hmacSHA256', Blob.valueOf(data), Blob.valueOf(key));
String result = urlSafeEncodeBase64(mac);
return result;
}
/* ACCESSOR METHODS FOR EXTERNAL TESTS */
public boolean test_buildOutgoingScope {
get {
if (!Test.isRunningTest()) throw new TestOnlyException('Test must be running to use this method');
return this.buildOutgoingScope;
}
}
public String test_appSid {
get {
if (!Test.isRunningTest()) throw new TestOnlyException('Test must be running to use this method');
return this.appSid;
}
}
public Map<String,String> test_outgoingParams {
get {
if (!Test.isRunningTest()) throw new TestOnlyException('Test must be running to use this method');
return this.outgoingParams;
}
}
public List<String> test_scopes {
get {
if (!Test.isRunningTest()) throw new TestOnlyException('Test must be running to use this method');
return this.scopes;
}
}
public String test_incomingClientName {
get {
if (!Test.isRunningTest()) throw new TestOnlyException('Test must be running to use this method');
return this.incomingClientName;
}
}
private class TestOnlyException extends Exception {}
}