File size: 11,194 Bytes
7b715bc | 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 | /*
Copyright 2019 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.
*/
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Http;
using Google.Apis.Requests;
using Google.Apis.Services;
using Google.Apis.Storage.v1;
using Google.Apis.Storage.v1.Data;
using IntegrationTests.Utils;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using static Google.Apis.Auth.OAuth2.GoogleCredential;
namespace IntegrationTests
{
public class PerCallAuthTests
{
[Fact]
public void ServiceAccountPerCallCredential()
{
// No auth in the client.
StorageService client = new StorageService(new BaseClientService.Initializer
{
ApplicationName = "IntegrationTest"
});
GoogleCredential credential = Helper.GetServiceCredential().CreateScoped(StorageService.Scope.DevstorageFullControl);
// Create a request with a per-call credential.
Buckets buckets = client.Buckets.List(Helper.GetProjectId()).AddCredential(credential).Execute();
// Check the response is sane.
Assert.NotNull(buckets.Items);
}
[Fact]
public void OverridesServiceCredentialWithPerCallCredential_Header()
{
// Broken credential in the client.
StorageService client = new StorageService(new BaseClientService.Initializer
{
ApplicationName = "IntegrationTest",
HttpClientInitializer = GoogleCredential.FromAccessToken("BROKEN_ACCESS_TOKEN")
});
GoogleCredential credential = Helper.GetServiceCredential().CreateScoped(StorageService.Scope.DevstorageFullControl);
// Create a request with a per-call credential.; this overrides the service-level credential.
Buckets buckets = client.Buckets.List(Helper.GetProjectId()).AddCredential(credential).Execute();
// Check the response is sane.
Assert.NotNull(buckets.Items);
}
private class RequestInterceptorCredentialWrapper : IConfigurableHttpClientInitializer, IHttpExecuteInterceptor
{
private AccessTokenCredential _credential;
public HttpRequestMessage Request { get; private set; }
public RequestInterceptorCredentialWrapper(string accessToken, IAccessMethod accessMethod) =>
_credential = new AccessTokenCredential(accessToken, accessMethod);
public void Initialize(ConfigurableHttpClient httpClient)
{
_credential.Initialize(httpClient);
httpClient.MessageHandler.AddExecuteInterceptor(this);
}
public Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Request = request;
return Task.FromResult(true);
}
}
private BucketsResource.ListRequest BuildListBucketsRequest(
RequestInterceptorCredentialWrapper serviceCredential, ICredential callCredential)
{
// Set one credential in the client
StorageService client = new StorageService(new BaseClientService.Initializer
{
ApplicationName = "IntegrationTest",
HttpClientInitializer = serviceCredential
}); ;
// Create a request with a per-call credential.; this overrides the service-level credential.
return client.Buckets.List(Helper.GetProjectId()).AddCredential(callCredential);
}
[Fact]
public void OverridesServiceCredentialWithPerCallCredential_QueryString()
{
#pragma warning disable CS0618 // Type or member is obsolete
var serviceCredential = new RequestInterceptorCredentialWrapper("SERVICE_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());
var callCredential = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());
#pragma warning restore CS0618 // Type or member is obsolete
var request = BuildListBucketsRequest(serviceCredential, callCredential);
// This should throw unauthorized, the credentials are fake, but let's make sure the
// request got to the server so we know all appropiate interceptors executed.
var exception = Assert.ThrowsAny<GoogleApiException>(() => request.Execute());
Assert.Equal(401, exception.Error.Code);
string query = serviceCredential.Request.RequestUri.Query;
Assert.DoesNotContain("access_token=SERVICE_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
Assert.Contains("access_token=CALL_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void OverridesServiceCredentialWithPerCallCredential_Mixed_Header_Query()
{
var serviceCredential = new RequestInterceptorCredentialWrapper("SERVICE_CREDENTIAL_TOKEN", new BearerToken.AuthorizationHeaderAccessMethod());
#pragma warning disable CS0618 // Type or member is obsolete
var callCredential = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());
#pragma warning restore CS0618 // Type or member is obsolete
var request = BuildListBucketsRequest(serviceCredential, callCredential);
// This should throw unauthorized, the credentials are fake, but let's make sure the
// request got to the server so we know all appropiate interceptors executed.
var exception = Assert.ThrowsAny<GoogleApiException>(() => request.Execute());
Assert.Equal(401, exception.Error.Code);
HttpRequestMessage httpRequest = serviceCredential.Request;
string query = httpRequest.RequestUri.Query;
Assert.Null(httpRequest.Headers.Authorization);
Assert.Contains("access_token=CALL_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void OverridesServiceCredentialWithPerCallCredential_Mixed_Query_Header()
{
#pragma warning disable CS0618 // Type or member is obsolete
var serviceCredential = new RequestInterceptorCredentialWrapper("SERVICE_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());
#pragma warning restore CS0618 // Type or member is obsolete
var callCredential = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN", new BearerToken.AuthorizationHeaderAccessMethod());
var request = BuildListBucketsRequest(serviceCredential, callCredential);
// This should throw unauthorized, the credentials are fake, but let's make sure the
// request got to the server so we know all appropiate interceptors executed.
var exception = Assert.ThrowsAny<GoogleApiException>(() => request.Execute());
Assert.Equal(401, exception.Error.Code);
HttpRequestMessage httpRequest = serviceCredential.Request;
string query = httpRequest.RequestUri.Query;
Assert.DoesNotContain("access_token=SERVICE_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
Assert.Equal("CALL_CREDENTIAL_TOKEN", httpRequest.Headers.Authorization.Parameter);
}
[Fact]
public void OverridesServiceCredentialWithPerCallCredential_TwoCallCredentials()
{
#pragma warning disable CS0618 // Type or member is obsolete
var serviceCredential = new RequestInterceptorCredentialWrapper("SERVICE_CREDENTIAL_TOKEN", new BearerToken.QueryParameterAccessMethod());
var callCredential1 = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN_1", new BearerToken.QueryParameterAccessMethod());
var callCredential2 = new AccessTokenCredential("CALL_CREDENTIAL_TOKEN_2", new BearerToken.QueryParameterAccessMethod());
#pragma warning restore CS0618 // Type or member is obsolete
var request = BuildListBucketsRequest(serviceCredential, callCredential1);
request.AddCredential(callCredential2);
// This should throw unauthorized, the credentials are fake, but let's make sure the
// request got to the server so we know all appropiate interceptors executed.
var exception = Assert.ThrowsAny<GoogleApiException>(() => request.Execute());
Assert.Equal(401, exception.Error.Code);
string query = serviceCredential.Request.RequestUri.Query;
int serviceIndex = query.IndexOf("access_token=SERVICE_CREDENTIAL_TOKEN", StringComparison.OrdinalIgnoreCase);
int call1Index = query.LastIndexOf("access_token=CALL_CREDENTIAL_TOKEN_1", StringComparison.OrdinalIgnoreCase);
int call2Index = query.LastIndexOf("access_token=CALL_CREDENTIAL_TOKEN_2", StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("access_token=SERVICE_CREDENTIAL_TOKEN", query, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("access_token=CALL_CREDENTIAL_TOKEN_1", query, StringComparison.OrdinalIgnoreCase);
Assert.Contains("access_token=CALL_CREDENTIAL_TOKEN_2", query, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void NullParameters()
{
StorageService client = new StorageService();
GoogleCredential credential = Helper.GetServiceCredential().CreateScoped(StorageService.Scope.DevstorageFullControl);
Assert.Throws<ArgumentNullException>(() => ((ClientServiceRequest)null).AddCredential(credential));
var request = client.Buckets.List(Helper.GetProjectId());
Assert.Throws<ArgumentNullException>(() => request.AddCredential(null));
}
private class CredentialNoInterceptors : ICredential
{
public Task<string> GetAccessTokenForRequestAsync(string authUri = null, CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
public void Initialize(ConfigurableHttpClient httpClient) => throw new NotImplementedException();
}
[Fact]
public void InvalidCredential()
{
StorageService client = new StorageService();
var credential = new CredentialNoInterceptors();
var request = client.Buckets.List(Helper.GetProjectId());
// Provided credential doesn't implement the required execute interceptor.
Assert.Throws<ArgumentException>(() => request.AddCredential(credential));
}
}
}
|