File size: 6,791 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
/*
Copyright 2022 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

    https://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.Apis.Http;
using Google.Apis.Json;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Google.Apis.Auth.OAuth2
{
    /// <summary>
    /// File-sourced credentials as described in
    /// https://google.aip.dev/auth/4117#determining-the-subject-token-in-file-sourced-credentials.
    /// </summary>
    /// <remarks>
    /// This credential type does not validate the credential configuration. A security 
    /// risk occurs when a credential configuration configured with malicious urls 
    /// is used.
    /// You should validate credential configurations provided by untrusted sources.
    /// See <see href="https://cloud.google.com/docs/authentication/external/externally-sourced-credentials">
    /// Security requirements when using credential configurations from an external source
    /// </see> for more details.
    /// </remarks>
    public sealed class FileSourcedExternalAccountCredential : ExternalAccountCredential, IGoogleCredential
    {
        new internal class Initializer : ExternalAccountCredential.Initializer
        {
            /// <summary>
            /// The file from which to obtain the subject token.
            /// </summary>
            internal string SubjectTokenFilePath { get; }

            /// <summary>
            /// If set, the subject token file content will be parsed as JSON and the
            /// value in the field with name <see cref="SubjectTokenJsonFieldName"/>
            /// will be returned as the subject token.
            /// </summary>
            internal string SubjectTokenJsonFieldName { get; set; }

            internal Initializer(string tokenUrl, string audience, string subjectTokenType, string subjectTokenFilePath)
                : base(tokenUrl, audience, subjectTokenType) => SubjectTokenFilePath = subjectTokenFilePath;

            internal Initializer(Initializer other) : base(other)
            {
                SubjectTokenFilePath = other.SubjectTokenFilePath;
                SubjectTokenJsonFieldName = other.SubjectTokenJsonFieldName;
            }

            internal Initializer(FileSourcedExternalAccountCredential other) : base(other)
            {
                SubjectTokenFilePath = other.SubjectTokenFilePath;
                SubjectTokenJsonFieldName = other.SubjectTokenJsonFieldName;
            }
        }

        /// <summary>
        /// The file path from which to obtain the subject token.
        /// </summary>
        public string SubjectTokenFilePath { get; }

        /// <summary>
        /// If set, the subject token file content will be parsed as JSON and the
        /// value in the field with name <see cref="SubjectTokenJsonFieldName"/>
        /// will be returned as the subject token.
        /// </summary>
        public string SubjectTokenJsonFieldName { get; }

        internal FileSourcedExternalAccountCredential(Initializer initializer) : base(initializer)
        {
            SubjectTokenFilePath = initializer.SubjectTokenFilePath;
            SubjectTokenJsonFieldName = initializer.SubjectTokenJsonFieldName;
        }

        /// <inheritdoc/>
        private protected override GoogleCredential WithoutImpersonationConfigurationImpl() =>
            ServiceAccountImpersonationUrl is null
            ? new GoogleCredential(this)
            : new GoogleCredential(new FileSourcedExternalAccountCredential(new Initializer(this)
            {
                ServiceAccountImpersonationUrl = null
            }));

        /// <inheritdoc/>
        protected override async Task<string> GetSubjectTokenAsyncImpl(CancellationToken taskCancellationToken)
        {
            var fileContent = await ReadSubjectTokenFileContentAsync().ConfigureAwait(false);
            string subjectToken;

            if (string.IsNullOrEmpty(SubjectTokenJsonFieldName))
            {
                subjectToken = fileContent;
            }
            else
            {
                var jsonResponse = NewtonsoftJsonSerializer.Instance.Deserialize<Dictionary<string, string>>(fileContent);

                subjectToken = jsonResponse[SubjectTokenJsonFieldName];
            }

            return subjectToken;

            async Task<string> ReadSubjectTokenFileContentAsync()
            {
                using var reader = File.OpenText(SubjectTokenFilePath);
                return await reader.ReadToEndAsync().ConfigureAwait(false);
            }
        }

        /// <inheritdoc/>
        string IGoogleCredential.QuotaProject => QuotaProject;

        /// <inheritdoc/>
        bool IGoogleCredential.HasExplicitScopes => HasExplicitScopes;

        /// <inheritdoc/>
        bool IGoogleCredential.SupportsExplicitScopes => SupportsExplicitScopes;

        /// <inheritdoc/>
        public GoogleCredential ToGoogleCredential() => new GoogleCredential(this);

        /// <inheritdoc/>
        Task<string> IGoogleCredential.GetUniverseDomainAsync(CancellationToken _) => Task.FromResult(UniverseDomain);

        /// <inheritdoc/>
        string IGoogleCredential.GetUniverseDomain() => UniverseDomain;

        /// <inheritdoc/>
        IGoogleCredential IGoogleCredential.WithQuotaProject(string quotaProject) =>
            new FileSourcedExternalAccountCredential(new Initializer(this) { QuotaProject = quotaProject });

        /// <inheritdoc/>
        IGoogleCredential IGoogleCredential.MaybeWithScopes(IEnumerable<string> scopes) =>
            new FileSourcedExternalAccountCredential(new Initializer(this) { Scopes = scopes });

        /// <inheritdoc/>
        IGoogleCredential IGoogleCredential.WithUserForDomainWideDelegation(string user) =>
            WithUserForDomainWideDelegation(user);

        /// <inheritdoc/>
        IGoogleCredential IGoogleCredential.WithHttpClientFactory(IHttpClientFactory httpClientFactory) =>
            new FileSourcedExternalAccountCredential(new Initializer(this) { HttpClientFactory = httpClientFactory });

        /// <inheritdoc/>
        IGoogleCredential IGoogleCredential.WithUniverseDomain(string universeDomain) =>
            new FileSourcedExternalAccountCredential(new Initializer(this) { UniverseDomain = universeDomain });
    }
}