UNPKG

11.5 kBJavaScriptView Raw
1// Copyright 2019 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14import { promisifyAll } from '@google-cloud/promisify';
15import { normalize } from './util.js';
16export var IAMExceptionMessages;
17(function (IAMExceptionMessages) {
18 IAMExceptionMessages["POLICY_OBJECT_REQUIRED"] = "A policy object is required.";
19 IAMExceptionMessages["PERMISSIONS_REQUIRED"] = "Permissions are required.";
20})(IAMExceptionMessages || (IAMExceptionMessages = {}));
21/**
22 * Get and set IAM policies for your Cloud Storage bucket.
23 *
24 * See {@link https://cloud.google.com/storage/docs/access-control/iam#short_title_iam_management| Cloud Storage IAM Management}
25 * See {@link https://cloud.google.com/iam/docs/granting-changing-revoking-access| Granting, Changing, and Revoking Access}
26 * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
27 *
28 * @constructor Iam
29 *
30 * @param {Bucket} bucket The parent instance.
31 * @example
32 * ```
33 * const {Storage} = require('@google-cloud/storage');
34 * const storage = new Storage();
35 * const bucket = storage.bucket('my-bucket');
36 * // bucket.iam
37 * ```
38 */
39class Iam {
40 constructor(bucket) {
41 this.request_ = bucket.request.bind(bucket);
42 this.resourceId_ = 'buckets/' + bucket.getId();
43 }
44 /**
45 * @typedef {object} GetPolicyOptions Requested options for IAM#getPolicy().
46 * @property {number} [requestedPolicyVersion] The version of IAM policies to
47 * request. If a policy with a condition is requested without setting
48 * this, the server will return an error. This must be set to a value
49 * of 3 to retrieve IAM policies containing conditions. This is to
50 * prevent client code that isn't aware of IAM conditions from
51 * interpreting and modifying policies incorrectly. The service might
52 * return a policy with version lower than the one that was requested,
53 * based on the feature syntax in the policy fetched.
54 * See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions}
55 * @property {string} [userProject] The ID of the project which will be
56 * billed for the request.
57 */
58 /**
59 * @typedef {array} GetPolicyResponse
60 * @property {Policy} 0 The policy.
61 * @property {object} 1 The full API response.
62 */
63 /**
64 * @typedef {object} Policy
65 * @property {PolicyBinding[]} policy.bindings Bindings associate members with roles.
66 * @property {string} [policy.etag] Etags are used to perform a read-modify-write.
67 * @property {number} [policy.version] The syntax schema version of the Policy.
68 * To set an IAM policy with conditional binding, this field must be set to
69 * 3 or greater.
70 * See {@link https://cloud.google.com/iam/docs/policies#versions| IAM Policy versions}
71 */
72 /**
73 * @typedef {object} PolicyBinding
74 * @property {string} role Role that is assigned to members.
75 * @property {string[]} members Specifies the identities requesting access for the bucket.
76 * @property {Expr} [condition] The condition that is associated with this binding.
77 */
78 /**
79 * @typedef {object} Expr
80 * @property {string} [title] An optional title for the expression, i.e. a
81 * short string describing its purpose. This can be used e.g. in UIs
82 * which allow to enter the expression.
83 * @property {string} [description] An optional description of the
84 * expression. This is a longer text which describes the expression,
85 * e.g. when hovered over it in a UI.
86 * @property {string} expression Textual representation of an expression in
87 * Common Expression Language syntax. The application context of the
88 * containing message determines which well-known feature set of CEL
89 * is supported.The condition that is associated with this binding.
90 *
91 * @see [Condition] https://cloud.google.com/storage/docs/access-control/iam#conditions
92 */
93 /**
94 * Get the IAM policy.
95 *
96 * @param {GetPolicyOptions} [options] Request options.
97 * @param {GetPolicyCallback} [callback] Callback function.
98 * @returns {Promise<GetPolicyResponse>}
99 *
100 * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/getIamPolicy| Buckets: setIamPolicy API Documentation}
101 *
102 * @example
103 * ```
104 * const {Storage} = require('@google-cloud/storage');
105 * const storage = new Storage();
106 * const bucket = storage.bucket('my-bucket');
107 *
108 * bucket.iam.getPolicy(
109 * {requestedPolicyVersion: 3},
110 * function(err, policy, apiResponse) {
111 *
112 * },
113 * );
114 *
115 * //-
116 * // If the callback is omitted, we'll return a Promise.
117 * //-
118 * bucket.iam.getPolicy({requestedPolicyVersion: 3})
119 * .then(function(data) {
120 * const policy = data[0];
121 * const apiResponse = data[1];
122 * });
123 *
124 * ```
125 * @example <caption>include:samples/iam.js</caption>
126 * region_tag:storage_view_bucket_iam_members
127 * Example of retrieving a bucket's IAM policy:
128 */
129 getPolicy(optionsOrCallback, callback) {
130 const { options, callback: cb } = normalize(optionsOrCallback, callback);
131 const qs = {};
132 if (options.userProject) {
133 qs.userProject = options.userProject;
134 }
135 if (options.requestedPolicyVersion !== null &&
136 options.requestedPolicyVersion !== undefined) {
137 qs.optionsRequestedPolicyVersion = options.requestedPolicyVersion;
138 }
139 this.request_({
140 uri: '/iam',
141 qs,
142 }, cb);
143 }
144 /**
145 * Set the IAM policy.
146 *
147 * @throws {Error} If no policy is provided.
148 *
149 * @param {Policy} policy The policy.
150 * @param {SetPolicyOptions} [options] Configuration options.
151 * @param {SetPolicyCallback} callback Callback function.
152 * @returns {Promise<SetPolicyResponse>}
153 *
154 * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/setIamPolicy| Buckets: setIamPolicy API Documentation}
155 * See {@link https://cloud.google.com/iam/docs/understanding-roles| IAM Roles}
156 *
157 * @example
158 * ```
159 * const {Storage} = require('@google-cloud/storage');
160 * const storage = new Storage();
161 * const bucket = storage.bucket('my-bucket');
162 *
163 * const myPolicy = {
164 * bindings: [
165 * {
166 * role: 'roles/storage.admin',
167 * members:
168 * ['serviceAccount:myotherproject@appspot.gserviceaccount.com']
169 * }
170 * ]
171 * };
172 *
173 * bucket.iam.setPolicy(myPolicy, function(err, policy, apiResponse) {});
174 *
175 * //-
176 * // If the callback is omitted, we'll return a Promise.
177 * //-
178 * bucket.iam.setPolicy(myPolicy).then(function(data) {
179 * const policy = data[0];
180 * const apiResponse = data[1];
181 * });
182 *
183 * ```
184 * @example <caption>include:samples/iam.js</caption>
185 * region_tag:storage_add_bucket_iam_member
186 * Example of adding to a bucket's IAM policy:
187 *
188 * @example <caption>include:samples/iam.js</caption>
189 * region_tag:storage_remove_bucket_iam_member
190 * Example of removing from a bucket's IAM policy:
191 */
192 setPolicy(policy, optionsOrCallback, callback) {
193 if (policy === null || typeof policy !== 'object') {
194 throw new Error(IAMExceptionMessages.POLICY_OBJECT_REQUIRED);
195 }
196 const { options, callback: cb } = normalize(optionsOrCallback, callback);
197 let maxRetries;
198 if (policy.etag === undefined) {
199 maxRetries = 0;
200 }
201 this.request_({
202 method: 'PUT',
203 uri: '/iam',
204 maxRetries,
205 json: Object.assign({
206 resourceId: this.resourceId_,
207 }, policy),
208 qs: options,
209 }, cb);
210 }
211 /**
212 * Test a set of permissions for a resource.
213 *
214 * @throws {Error} If permissions are not provided.
215 *
216 * @param {string|string[]} permissions The permission(s) to test for.
217 * @param {TestIamPermissionsOptions} [options] Configuration object.
218 * @param {TestIamPermissionsCallback} [callback] Callback function.
219 * @returns {Promise<TestIamPermissionsResponse>}
220 *
221 * See {@link https://cloud.google.com/storage/docs/json_api/v1/buckets/testIamPermissions| Buckets: testIamPermissions API Documentation}
222 *
223 * @example
224 * ```
225 * const {Storage} = require('@google-cloud/storage');
226 * const storage = new Storage();
227 * const bucket = storage.bucket('my-bucket');
228 *
229 * //-
230 * // Test a single permission.
231 * //-
232 * const test = 'storage.buckets.delete';
233 *
234 * bucket.iam.testPermissions(test, function(err, permissions, apiResponse) {
235 * console.log(permissions);
236 * // {
237 * // "storage.buckets.delete": true
238 * // }
239 * });
240 *
241 * //-
242 * // Test several permissions at once.
243 * //-
244 * const tests = [
245 * 'storage.buckets.delete',
246 * 'storage.buckets.get'
247 * ];
248 *
249 * bucket.iam.testPermissions(tests, function(err, permissions) {
250 * console.log(permissions);
251 * // {
252 * // "storage.buckets.delete": false,
253 * // "storage.buckets.get": true
254 * // }
255 * });
256 *
257 * //-
258 * // If the callback is omitted, we'll return a Promise.
259 * //-
260 * bucket.iam.testPermissions(test).then(function(data) {
261 * const permissions = data[0];
262 * const apiResponse = data[1];
263 * });
264 * ```
265 */
266 testPermissions(permissions, optionsOrCallback, callback) {
267 if (!Array.isArray(permissions) && typeof permissions !== 'string') {
268 throw new Error(IAMExceptionMessages.PERMISSIONS_REQUIRED);
269 }
270 const { options, callback: cb } = normalize(optionsOrCallback, callback);
271 const permissionsArray = Array.isArray(permissions)
272 ? permissions
273 : [permissions];
274 const req = Object.assign({
275 permissions: permissionsArray,
276 }, options);
277 this.request_({
278 uri: '/iam/testPermissions',
279 qs: req,
280 useQuerystring: true,
281 }, (err, resp) => {
282 if (err) {
283 cb(err, null, resp);
284 return;
285 }
286 const availablePermissions = Array.isArray(resp.permissions)
287 ? resp.permissions
288 : [];
289 const permissionsHash = permissionsArray.reduce((acc, permission) => {
290 acc[permission] = availablePermissions.indexOf(permission) > -1;
291 return acc;
292 }, {});
293 cb(null, permissionsHash, resp);
294 });
295 }
296}
297/*! Developer Documentation
298 *
299 * All async methods (except for streams) will return a Promise in the event
300 * that a callback is omitted.
301 */
302promisifyAll(Iam);
303export { Iam };