id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
162,024 | #求序列的N日平均值,返回序列
return pd.Series(S).rolling(N).mean().values
def REF(S, N=1): #对序列整体下移动N,返回序列(shift后会产生NAN)
return pd.Series(S).shift(N).values
def EMV(HIGH,LOW,VOL,N=14,M=9): #简易波动指标
VOLUME=MA(VOL,N)/VOL; MID=100*(HIGH+LOW-REF(HIGH+LOW,1))/(HIGH+LOW)
EMV=MA(MID*VOLUME*(HIGH-LOW)/MA(HIGH-LOW,N),N); MAEMV=MA(EMV,M)
return EMV,MAEMV | null |
162,025 | #求序列的N日平均值,返回序列
return pd.Series(S).rolling(N).mean().values
def REF(S, N=1): #对序列整体下移动N,返回序列(shift后会产生NAN)
return pd.Series(S).shift(N).values
def DPO(CLOSE,M1=20, M2=10, M3=6): #区间震荡线
DPO = CLOSE - REF(MA(CLOSE, M1), M2); MADPO = MA(DPO, M3)
return DPO, MADPO | null |
162,026 | #对序列整体下移动N,返回序列(shift后会产生NAN)
return pd.Series(S).shift(N).values
def SUM(S, N): #对序列求N天累计和,返回序列
return pd.Series(S).rolling(N).sum().values
def BRAR(OPEN,CLOSE,HIGH,LOW,M1=26): #BRAR-ARBR 情绪指标
AR = SUM(HIGH - OPEN, M1) / SUM(OPEN - LOW, M1) * 100
BR = SUM(MAX(0, HIGH - REF(CLOSE, 1)), M1) / SUM(MAX(0, REF(CLOSE, 1) - LOW), M1) * 100
return AR, BR | null |
162,027 | #求序列的N日平均值,返回序列
return pd.Series(S).rolling(N).mean().values
def DMA(CLOSE,N1=10,N2=50,M=10): #平行线差指标
DIF=MA(CLOSE,N1)-MA(CLOSE,N2); DIFMA=MA(DIF,M)
return DIF,DIFMA | null |
162,028 | #求序列的N日平均值,返回序列
return pd.Series(S).rolling(N).mean().values
def REF(S, N=1): #对序列整体下移动N,返回序列(shift后会产生NAN)
return pd.Series(S).shift(N).values
def MTM(CLOSE,N=12,M=6): #动量指标
MTM=CLOSE-REF(CLOSE,N); MTMMA=MA(MTM,M)
return MTM,MTMMA | null |
162,029 | #求序列的N日平均值,返回序列
return pd.Series(S).rolling(N).mean().values
def REF(S, N=1): #对序列整体下移动N,返回序列(shift后会产生NAN)
return pd.Series(S).shift(N).values
def ROC(CLOSE,N=12,M=6): #变动率指标
ROC=100*(CLOSE-REF(CLOSE,N))/REF(CLOSE,N); MAROC=MA(ROC,M)
return ROC,MAROC | null |
162,030 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
def setup_tf():
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.logging.set_verbosity(tf.logging.ERROR) | null |
162,031 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
def smart_shape(x):
s = x.shape
st = tf.shape(x)
return [s[i] if s[i].value is not None else st[i] for i in range(4)] | null |
162,032 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
The provided code snippet includes necessary dependencies for implementing the `ilog2` function. Write a Python function `def ilog2(x)` to solve the following problem:
Integer log2.
Here is the function:
def ilog2(x):
"""Integer log2."""
return int(np.ceil(np.log2(x))) | Integer log2. |
162,033 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
def get_latest_global_step(dir):
"""Loads the global step from the latest checkpoint in directory.
Args:
dir: string, path to the checkpoint directory.
Returns:
int, the global step of the latest checkpoint or 0 if none was found.
"""
try:
checkpoint_reader = tf.train.NewCheckpointReader(find_latest_checkpoint(dir))
return checkpoint_reader.get_tensor(tf.GraphKeys.GLOBAL_STEP)
except: # pylint: disable=bare-except
return 0
The provided code snippet includes necessary dependencies for implementing the `get_latest_global_step_in_subdir` function. Write a Python function `def get_latest_global_step_in_subdir(dir)` to solve the following problem:
Loads the global step from the latest checkpoint in sub-directories. Args: dir: string, parent of the checkpoint directories. Returns: int, the global step of the latest checkpoint or 0 if none was found.
Here is the function:
def get_latest_global_step_in_subdir(dir):
"""Loads the global step from the latest checkpoint in sub-directories.
Args:
dir: string, parent of the checkpoint directories.
Returns:
int, the global step of the latest checkpoint or 0 if none was found.
"""
sub_dirs = (x for x in glob.glob(os.path.join(dir, '*')) if os.path.isdir(x))
step = 0
for x in sub_dirs:
step = max(step, get_latest_global_step(x))
return step | Loads the global step from the latest checkpoint in sub-directories. Args: dir: string, parent of the checkpoint directories. Returns: int, the global step of the latest checkpoint or 0 if none was found. |
162,034 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
The provided code snippet includes necessary dependencies for implementing the `getter_ema` function. Write a Python function `def getter_ema(ema, getter, name, *args, **kwargs)` to solve the following problem:
Exponential moving average getter for variable scopes. Args: ema: ExponentialMovingAverage object, where to get variable moving averages. getter: default variable scope getter. name: variable name. *args: extra args passed to default getter. **kwargs: extra args passed to default getter. Returns: If found the moving average variable, otherwise the default variable.
Here is the function:
def getter_ema(ema, getter, name, *args, **kwargs):
"""Exponential moving average getter for variable scopes.
Args:
ema: ExponentialMovingAverage object, where to get variable moving averages.
getter: default variable scope getter.
name: variable name.
*args: extra args passed to default getter.
**kwargs: extra args passed to default getter.
Returns:
If found the moving average variable, otherwise the default variable.
"""
var = getter(name, *args, **kwargs)
ema_var = ema.average(var)
return ema_var if ema_var else var | Exponential moving average getter for variable scopes. Args: ema: ExponentialMovingAverage object, where to get variable moving averages. getter: default variable scope getter. name: variable name. *args: extra args passed to default getter. **kwargs: extra args passed to default getter. Returns: If found the moving average variable, otherwise the default variable. |
162,035 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
def model_vars(scope=None):
return tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope) | null |
162,036 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
The provided code snippet includes necessary dependencies for implementing the `average_gradients` function. Write a Python function `def average_gradients(tower_grads)` to solve the following problem:
Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. For each tower, a list of its gradients. Returns: List of pairs of (gradient, variable) where the gradient has been averaged across all towers.
Here is the function:
def average_gradients(tower_grads):
# Adapted from:
# https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train.py
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. For each tower, a list of its gradients.
Returns:
List of pairs of (gradient, variable) where the gradient has been averaged
across all towers.
"""
if len(tower_grads) <= 1:
return tower_grads[0]
average_grads = []
for grads_and_vars in zip(*tower_grads):
grad = tf.reduce_mean([gv[0] for gv in grads_and_vars], 0)
average_grads.append((grad, grads_and_vars[0][1]))
return average_grads | Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. For each tower, a list of its gradients. Returns: List of pairs of (gradient, variable) where the gradient has been averaged across all towers. |
162,037 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
def gpu(x):
return '/gpu:%d' % (x % max(1, len(get_available_gpus())))
def get_available_gpus():
global _GPUS
if _GPUS is None:
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
local_device_protos = device_lib.list_local_devices(session_config=config)
_GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU'])
return _GPUS
The provided code snippet includes necessary dependencies for implementing the `para_list` function. Write a Python function `def para_list(fn, *args)` to solve the following problem:
Run on multiple GPUs in parallel and return list of results.
Here is the function:
def para_list(fn, *args):
"""Run on multiple GPUs in parallel and return list of results."""
gpus = len(get_available_gpus())
if gpus <= 1:
return zip(*[fn(*args)])
splitted = [tf.split(x, gpus) for x in args]
outputs = []
for gpu, x in enumerate(zip(*splitted)):
with tf.name_scope('tower%d' % gpu):
with tf.device(tf.train.replica_device_setter(
worker_device='/gpu:%d' % gpu, ps_device='/cpu:0', ps_tasks=1)):
outputs.append(fn(*x))
return zip(*outputs) | Run on multiple GPUs in parallel and return list of results. |
162,038 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
def gpu(x):
return '/gpu:%d' % (x % max(1, len(get_available_gpus())))
def get_available_gpus():
global _GPUS
if _GPUS is None:
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
local_device_protos = device_lib.list_local_devices(session_config=config)
_GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU'])
return _GPUS
The provided code snippet includes necessary dependencies for implementing the `para_mean` function. Write a Python function `def para_mean(fn, *args)` to solve the following problem:
Run on multiple GPUs in parallel and return means.
Here is the function:
def para_mean(fn, *args):
"""Run on multiple GPUs in parallel and return means."""
gpus = len(get_available_gpus())
if gpus <= 1:
return fn(*args)
splitted = [tf.split(x, gpus) for x in args]
outputs = []
for gpu, x in enumerate(zip(*splitted)):
with tf.name_scope('tower%d' % gpu):
with tf.device(tf.train.replica_device_setter(
worker_device='/gpu:%d' % gpu, ps_device='/cpu:0', ps_tasks=1)):
outputs.append(fn(*x))
if isinstance(outputs[0], (tuple, list)):
return [tf.reduce_mean(x, 0) for x in zip(*outputs)]
return tf.reduce_mean(outputs, 0) | Run on multiple GPUs in parallel and return means. |
162,039 | import glob
import os
import re
from absl import flags
import numpy as np
import tensorflow as tf
from tensorflow.python.client import device_lib
def gpu(x):
return '/gpu:%d' % (x % max(1, len(get_available_gpus())))
def get_available_gpus():
global _GPUS
if _GPUS is None:
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
local_device_protos = device_lib.list_local_devices(session_config=config)
_GPUS = tuple([x.name for x in local_device_protos if x.device_type == 'GPU'])
return _GPUS
The provided code snippet includes necessary dependencies for implementing the `para_cat` function. Write a Python function `def para_cat(fn, *args)` to solve the following problem:
Run on multiple GPUs in parallel and return concatenated outputs.
Here is the function:
def para_cat(fn, *args):
"""Run on multiple GPUs in parallel and return concatenated outputs."""
gpus = len(get_available_gpus())
if gpus <= 1:
return fn(*args)
splitted = [tf.split(x, gpus) for x in args]
outputs = []
for gpu, x in enumerate(zip(*splitted)):
with tf.name_scope('tower%d' % gpu):
with tf.device(tf.train.replica_device_setter(
worker_device='/gpu:%d' % gpu, ps_device='/cpu:0', ps_tasks=1)):
outputs.append(fn(*x))
if isinstance(outputs[0], (tuple, list)):
return [tf.concat(x, axis=0) for x in zip(*outputs)]
return tf.concat(outputs, axis=0) | Run on multiple GPUs in parallel and return concatenated outputs. |
162,040 | import glob
import itertools
import os
import numpy as np
import tensorflow as tf
from absl import flags
from tqdm import tqdm
from libml import utils
FLAGS = flags.FLAGS
def record_parse(serialized_example):
features = tf.parse_single_example(
serialized_example,
features={'image': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64)})
image = tf.image.decode_image(features['image'])
image = tf.cast(image, tf.float32) * (2.0 / 255) - 1.0
label = features['label']
return dict(image=image, label=label)
def default_parse(dataset: tf.data.Dataset, parse_fn=record_parse) -> tf.data.Dataset:
para = 4 * max(1, len(utils.get_available_gpus())) * FLAGS.para_parse
return dataset.map(parse_fn, num_parallel_calls=para) | null |
162,041 | import glob
import itertools
import os
import numpy as np
import tensorflow as tf
from absl import flags
from tqdm import tqdm
from libml import utils
FLAGS = flags.FLAGS
def memoize(dataset: tf.data.Dataset) -> tf.data.Dataset:
data = []
with tf.Session(config=utils.get_config()) as session:
dataset = dataset.prefetch(16)
it = dataset.make_one_shot_iterator().get_next()
try:
while 1:
data.append(session.run(it))
except tf.errors.OutOfRangeError:
pass
images = np.stack([x['image'] for x in data])
labels = np.stack([x['label'] for x in data])
def tf_get(index):
def get(index):
return images[index], labels[index]
image, label = tf.py_func(get, [index], [tf.float32, tf.int64])
return dict(image=image, label=label)
dataset = tf.data.Dataset.range(len(data)).repeat()
dataset = dataset.shuffle(len(data) if len(data) < FLAGS.shuffle else FLAGS.shuffle)
return dataset.map(tf_get) | null |
162,042 | import glob
import itertools
import os
import numpy as np
import tensorflow as tf
from absl import flags
from tqdm import tqdm
from libml import utils
def augment_mirror(x):
return tf.image.random_flip_left_right(x) | null |
162,043 | import glob
import itertools
import os
import numpy as np
import tensorflow as tf
from absl import flags
from tqdm import tqdm
from libml import utils
def augment_shift(x, w):
y = tf.pad(x, [[w] * 2, [w] * 2, [0] * 2], mode='REFLECT')
return tf.random_crop(y, tf.shape(x)) | null |
162,044 | import glob
import itertools
import os
import numpy as np
import tensorflow as tf
from absl import flags
from tqdm import tqdm
from libml import utils
def augment_noise(x, std):
return x + std * tf.random_normal(tf.shape(x), dtype=x.dtype) | null |
162,045 | import glob
import itertools
import os
import numpy as np
import tensorflow as tf
from absl import flags
from tqdm import tqdm
from libml import utils
def compute_mean_std(data: tf.data.Dataset):
data = data.map(lambda x: x['image']).batch(1024).prefetch(1)
data = data.make_one_shot_iterator().get_next()
count = 0
stats = []
with tf.Session(config=utils.get_config()) as sess:
def iterator():
while True:
try:
yield sess.run(data)
except tf.errors.OutOfRangeError:
break
for batch in tqdm(iterator(), unit='kimg', desc='Computing dataset mean and std'):
ratio = batch.shape[0] / 1024.
count += ratio
stats.append((batch.mean((0, 1, 2)) * ratio, (batch ** 2).mean((0, 1, 2)) * ratio))
mean = sum(x[0] for x in stats) / count
sigma = sum(x[1] for x in stats) / count - mean ** 2
std = np.sqrt(sigma)
print('Mean %s Std: %s' % (mean, std))
return mean, std | null |
162,046 | import tensorflow as tf
from libml.data import DataSet
def smart_shape(x):
s, t = x.shape, tf.shape(x)
return [t[i] if s[i].value is None else s[i] for i in range(len(s))] | null |
162,047 | import tensorflow as tf
from libml.data import DataSet
def entropy_from_logits(logits):
"""Computes entropy from classifier logits.
Args:
logits: a tensor of shape (batch_size, class_count) representing the
logits of a classifier.
Returns:
A tensor of shape (batch_size,) of floats giving the entropies
batchwise.
"""
distribution = tf.contrib.distributions.Categorical(logits=logits)
return distribution.entropy()
The provided code snippet includes necessary dependencies for implementing the `entropy_penalty` function. Write a Python function `def entropy_penalty(logits, entropy_penalty_multiplier, mask)` to solve the following problem:
Computes an entropy penalty using the classifier logits. Args: logits: a tensor of shape (batch_size, class_count) representing the logits of a classifier. entropy_penalty_multiplier: A float by which the entropy is multiplied. mask: A tensor that optionally masks out some of the costs. Returns: The mean entropy penalty
Here is the function:
def entropy_penalty(logits, entropy_penalty_multiplier, mask):
"""Computes an entropy penalty using the classifier logits.
Args:
logits: a tensor of shape (batch_size, class_count) representing the
logits of a classifier.
entropy_penalty_multiplier: A float by which the entropy is multiplied.
mask: A tensor that optionally masks out some of the costs.
Returns:
The mean entropy penalty
"""
entropy = entropy_from_logits(logits)
losses = entropy * entropy_penalty_multiplier
losses *= tf.cast(mask, tf.float32)
return tf.reduce_mean(losses) | Computes an entropy penalty using the classifier logits. Args: logits: a tensor of shape (batch_size, class_count) representing the logits of a classifier. entropy_penalty_multiplier: A float by which the entropy is multiplied. mask: A tensor that optionally masks out some of the costs. Returns: The mean entropy penalty |
162,048 | import tensorflow as tf
from libml.data import DataSet
The provided code snippet includes necessary dependencies for implementing the `kl_divergence_from_logits` function. Write a Python function `def kl_divergence_from_logits(logits_a, logits_b)` to solve the following problem:
Gets KL divergence from logits parameterizing categorical distributions. Args: logits_a: A tensor of logits parameterizing the first distribution. logits_b: A tensor of logits parameterizing the second distribution. Returns: The (batch_size,) shaped tensor of KL divergences.
Here is the function:
def kl_divergence_from_logits(logits_a, logits_b):
"""Gets KL divergence from logits parameterizing categorical distributions.
Args:
logits_a: A tensor of logits parameterizing the first distribution.
logits_b: A tensor of logits parameterizing the second distribution.
Returns:
The (batch_size,) shaped tensor of KL divergences.
"""
distribution1 = tf.contrib.distributions.Categorical(logits=logits_a)
distribution2 = tf.contrib.distributions.Categorical(logits=logits_b)
return tf.contrib.distributions.kl_divergence(distribution1, distribution2) | Gets KL divergence from logits parameterizing categorical distributions. Args: logits_a: A tensor of logits parameterizing the first distribution. logits_b: A tensor of logits parameterizing the second distribution. Returns: The (batch_size,) shaped tensor of KL divergences. |
162,049 | import tensorflow as tf
from libml.data import DataSet
The provided code snippet includes necessary dependencies for implementing the `mse_from_logits` function. Write a Python function `def mse_from_logits(output_logits, target_logits)` to solve the following problem:
Computes MSE between predictions associated with logits. Args: output_logits: A tensor of logits from the primary model. target_logits: A tensor of logits from the secondary model. Returns: The mean MSE
Here is the function:
def mse_from_logits(output_logits, target_logits):
"""Computes MSE between predictions associated with logits.
Args:
output_logits: A tensor of logits from the primary model.
target_logits: A tensor of logits from the secondary model.
Returns:
The mean MSE
"""
diffs = tf.nn.softmax(output_logits) - tf.nn.softmax(target_logits)
squared_diffs = tf.square(diffs)
return tf.reduce_mean(squared_diffs, -1) | Computes MSE between predictions associated with logits. Args: output_logits: A tensor of logits from the primary model. target_logits: A tensor of logits from the secondary model. Returns: The mean MSE |
162,050 | import tensorflow as tf
from libml.data import DataSet
def interleave_offsets(batch, nu):
groups = [batch // (nu + 1)] * (nu + 1)
for x in range(batch - sum(groups)):
groups[-x - 1] += 1
offsets = [0]
for g in groups:
offsets.append(offsets[-1] + g)
assert offsets[-1] == batch
return offsets
def interleave(xy, batch):
nu = len(xy) - 1
offsets = interleave_offsets(batch, nu)
xy = [[v[offsets[p]:offsets[p + 1]] for p in range(nu + 1)] for v in xy]
for i in range(1, nu + 1):
xy[0][i], xy[i][i] = xy[i][i], xy[0][i]
return [tf.concat(v, axis=0) for v in xy] | null |
162,051 | import tensorflow as tf
from libml.data import DataSet
def renorm(v):
return v / tf.reduce_sum(v, axis=-1, keepdims=True) | null |
162,052 | import tensorflow as tf
from libml.data import DataSet
def shakeshake(a, b, training):
if not training:
return 0.5 * (a + b)
mu = tf.random_uniform([tf.shape(a)[0]] + [1] * (len(a.shape) - 1), 0, 1)
mixf = a + mu * (b - a)
mixb = a + mu[::1] * (b - a)
return tf.stop_gradient(mixf - mixb) + mixb | null |
162,053 | import itertools
from absl import flags
from libml.data import DataSet, augment_cifar10, augment_svhn, augment_stl10
import tensorflow as tf
FLAGS = flags.FLAGS
def stack_augment(augment):
def func(x):
xl = [augment(x) for _ in range(FLAGS.nu)]
return dict(image=tf.stack([x['image'] for x in xl]),
label=tf.stack([x['label'] for x in xl]))
return func | null |
162,054 | import collections
import functools
import json
import os
import sys
import tempfile
from urllib import request
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
URLS = {
'svhn': 'http://ufldl.stanford.edu/housenumbers/{}_32x32.mat',
}
def _encode_png(images):
raw = []
with tf.Session() as sess, tf.device('cpu:0'):
image_x = tf.placeholder(tf.uint8, [None, None, None], 'image_x')
to_png = tf.image.encode_png(image_x)
for x in trange(images.shape[0], desc='PNG Encoding', leave=False):
raw.append(sess.run(to_png, feed_dict={image_x: images[x]}))
return raw
def _load_private_svhn(name=None):
splits = collections.OrderedDict()
for split in ['test']:
with tempfile.NamedTemporaryFile() as f:
request.urlretrieve(URLS['svhn'].format(split), f.name)
data_dict = scipy.io.loadmat(f.name)
dataset = {}
dataset['images'] = np.transpose(data_dict['X'], [3, 0, 1, 2])
dataset['images'] = _encode_png(dataset['images'])
dataset['labels'] = data_dict['y'].reshape((-1))
# SVHN raw data uses labels from 1 to 10; use 0 to 9 instead.
dataset['labels'] -= 1
if split == 'test':
# svhnxxx, the xxx number is a setting for the privacy algorithm: the number of teachers that voted for
# the same class.
if name == 'svhn300':
private_labels_file = 'data/privacy/svhn_noisy_labels_gnmax_t300_ts_200_n_40_david_convention.json'
elif name == 'svhn500':
private_labels_file = 'data/privacy/svhn_noisy_labels_gnmax_t500_ts_200_n_40_david_convention.json'
elif name == 'svhn200':
private_labels_file = 'data/privacy/svhn_noisy_labels_gnmax_t200_ts_200_n_40_david_convention.json'
elif name == 'svhn200s150':
private_labels_file = 'data/privacy/svhn_noisy_labels_gnmax_t200_ts_150_n_40_david_convention.json'
dataset['labels'][:10000] = json.load(open(private_labels_file, 'r'))['label'][:10000]
splits['train'] = dict(images=dataset['images'][:10000], labels=dataset['labels'][:10000])
splits['test'] = dict(images=dataset['images'][10000:], labels=dataset['labels'][10000:])
else:
splits[split] = dataset
return splits | null |
162,055 | import collections
import functools
import json
import os
import sys
import tempfile
from urllib import request
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
DATA_DIR = os.environ['ML_DATA']
def _save_as_tfrecord(data, filename):
assert len(data['images']) == len(data['labels'])
filename = os.path.join(DATA_DIR, filename + '.tfrecord')
print('Saving dataset:', filename)
with tf.python_io.TFRecordWriter(filename) as writer:
for x in trange(len(data['images']), desc='Building records'):
feat = dict(image=_bytes_feature(data['images'][x]),
label=_int64_feature(data['labels'][x]))
record = tf.train.Example(features=tf.train.Features(feature=feat))
writer.write(record.SerializeToString())
print('Saved:', filename) | null |
162,056 | import collections
import functools
import json
import os
import sys
import tempfile
from urllib import request
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
DATA_DIR = os.environ['ML_DATA']
def _is_installed(name, checksums):
for subset, checksum in checksums.items():
filename = os.path.join(DATA_DIR, '%s-%s.tfrecord' % (name, subset))
if not os.path.exists(filename):
return False
return True | null |
162,057 | import collections
import functools
import json
import os
import sys
import tempfile
from urllib import request
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
DATA_DIR = os.environ['ML_DATA']
def _save_files(files, *args, **kwargs):
del args, kwargs
for folder in frozenset(os.path.dirname(x) for x in files):
os.makedirs(os.path.join(DATA_DIR, folder), exist_ok=True)
for filename, contents in files.items():
with open(os.path.join(DATA_DIR, filename), 'w') as f:
f.write(contents) | null |
162,058 | import collections
import functools
import json
import os
import sys
import tempfile
from urllib import request
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
DATA_DIR = os.environ['ML_DATA']
def _is_installed_folder(name, folder):
return os.path.exists(os.path.join(DATA_DIR, name, folder)) | null |
162,059 | from collections import defaultdict
import json
import os
from absl import app
from absl import flags
from libml import utils
import numpy as np
import tensorflow as tf
from tqdm import trange, tqdm
from libml.data import DATA_DIR
def get_class(serialized_example):
return tf.parse_single_example(serialized_example, features={'label': tf.FixedLenFeature([], tf.int64)})['label'] | null |
162,060 | import tensorflow as tf
def kl_divergence_with_logit(q_logit, p_logit):
"""Compute the per-element KL-divergence of a batch."""
q = tf.nn.softmax(q_logit)
qlogq = tf.reduce_sum(q * logsoftmax(q_logit), 1)
qlogp = tf.reduce_sum(q * logsoftmax(p_logit), 1)
return qlogq - qlogp
def get_normalized_vector(d):
"""Normalize d by infinity and L2 norms."""
d /= 1e-12 + tf.reduce_max(
tf.abs(d), list(range(1, len(d.get_shape()))), keepdims=True
)
d /= tf.sqrt(
1e-6
+ tf.reduce_sum(
tf.pow(d, 2.0), list(range(1, len(d.get_shape()))), keepdims=True
)
)
return d
The provided code snippet includes necessary dependencies for implementing the `generate_perturbation` function. Write a Python function `def generate_perturbation(x, logit, forward, epsilon, xi=1e-6)` to solve the following problem:
Generate an adversarial perturbation. Args: x: Model inputs. logit: Original model output without perturbation. forward: Callable which computs logits given input. epsilon: Gradient multiplier. xi: Small constant. Returns: Aversarial perturbation to be applied to x.
Here is the function:
def generate_perturbation(x, logit, forward, epsilon, xi=1e-6):
"""Generate an adversarial perturbation.
Args:
x: Model inputs.
logit: Original model output without perturbation.
forward: Callable which computs logits given input.
epsilon: Gradient multiplier.
xi: Small constant.
Returns:
Aversarial perturbation to be applied to x.
"""
d = tf.random_normal(shape=tf.shape(x))
for _ in range(1):
d = xi * get_normalized_vector(d)
logit_p = logit
logit_m = forward(x + d)
dist = kl_divergence_with_logit(logit_p, logit_m)
grad = tf.gradients(tf.reduce_mean(dist), [d], aggregation_method=2)[0]
d = tf.stop_gradient(grad)
return epsilon * get_normalized_vector(d) | Generate an adversarial perturbation. Args: x: Model inputs. logit: Original model output without perturbation. forward: Callable which computs logits given input. epsilon: Gradient multiplier. xi: Small constant. Returns: Aversarial perturbation to be applied to x. |
162,061 | import collections
import gzip
import os
import sys
import tarfile
import tempfile
from urllib import request
from easydict import EasyDict
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
URLS = {
'svhn': 'http://ufldl.stanford.edu/housenumbers/{}_32x32.mat',
'cifar10': 'https://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz',
'cifar100': 'https://www.cs.toronto.edu/~kriz/cifar-100-matlab.tar.gz',
'stl10': 'http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz',
}
def _encode_png(images):
raw = []
with tf.Session() as sess, tf.device('cpu:0'):
image_x = tf.placeholder(tf.uint8, [None, None, None], 'image_x')
to_png = tf.image.encode_png(image_x)
for x in trange(images.shape[0], desc='PNG Encoding', leave=False):
raw.append(sess.run(to_png, feed_dict={image_x: images[x]}))
return raw
def _load_svhn():
splits = collections.OrderedDict()
for split in ['train', 'test', 'extra']:
with tempfile.NamedTemporaryFile() as f:
request.urlretrieve(URLS['svhn'].format(split), f.name)
data_dict = scipy.io.loadmat(f.name)
dataset = {}
dataset['images'] = np.transpose(data_dict['X'], [3, 0, 1, 2])
dataset['images'] = _encode_png(dataset['images'])
dataset['labels'] = data_dict['y'].reshape((-1))
# SVHN raw data uses labels from 1 to 10; use 0 to 9 instead.
dataset['labels'] -= 1
splits[split] = dataset
return splits | null |
162,062 | import collections
import gzip
import os
import sys
import tarfile
import tempfile
from urllib import request
from easydict import EasyDict
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
URLS = {
'svhn': 'http://ufldl.stanford.edu/housenumbers/{}_32x32.mat',
'cifar10': 'https://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz',
'cifar100': 'https://www.cs.toronto.edu/~kriz/cifar-100-matlab.tar.gz',
'stl10': 'http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz',
}
def _encode_png(images):
raw = []
with tf.Session() as sess, tf.device('cpu:0'):
image_x = tf.placeholder(tf.uint8, [None, None, None], 'image_x')
to_png = tf.image.encode_png(image_x)
for x in trange(images.shape[0], desc='PNG Encoding', leave=False):
raw.append(sess.run(to_png, feed_dict={image_x: images[x]}))
return raw
def _load_stl10():
def unflatten(images):
return np.transpose(images.reshape((-1, 3, 96, 96)),
[0, 3, 2, 1])
with tempfile.NamedTemporaryFile() as f:
if os.path.exists('stl10/stl10_binary.tar.gz'):
f = open('stl10/stl10_binary.tar.gz', 'rb')
else:
request.urlretrieve(URLS['stl10'], f.name)
tar = tarfile.open(fileobj=f)
train_X = tar.extractfile('stl10_binary/train_X.bin')
train_y = tar.extractfile('stl10_binary/train_y.bin')
test_X = tar.extractfile('stl10_binary/test_X.bin')
test_y = tar.extractfile('stl10_binary/test_y.bin')
unlabeled_X = tar.extractfile('stl10_binary/unlabeled_X.bin')
train_set = {'images': np.frombuffer(train_X.read(), dtype=np.uint8),
'labels': np.frombuffer(train_y.read(), dtype=np.uint8) - 1}
test_set = {'images': np.frombuffer(test_X.read(), dtype=np.uint8),
'labels': np.frombuffer(test_y.read(), dtype=np.uint8) - 1}
_imgs = np.frombuffer(unlabeled_X.read(), dtype=np.uint8)
unlabeled_set = {'images': _imgs,
'labels': np.zeros(100000, dtype=np.uint8)}
fold_indices = tar.extractfile('stl10_binary/fold_indices.txt').read()
train_set['images'] = _encode_png(unflatten(train_set['images']))
test_set['images'] = _encode_png(unflatten(test_set['images']))
unlabeled_set['images'] = _encode_png(unflatten(unlabeled_set['images']))
return dict(train=train_set, test=test_set, unlabeled=unlabeled_set,
files=[EasyDict(filename="stl10_fold_indices.txt", data=fold_indices)]) | null |
162,063 | import collections
import gzip
import os
import sys
import tarfile
import tempfile
from urllib import request
from easydict import EasyDict
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
URLS = {
'svhn': 'http://ufldl.stanford.edu/housenumbers/{}_32x32.mat',
'cifar10': 'https://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz',
'cifar100': 'https://www.cs.toronto.edu/~kriz/cifar-100-matlab.tar.gz',
'stl10': 'http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz',
}
def _encode_png(images):
raw = []
with tf.Session() as sess, tf.device('cpu:0'):
image_x = tf.placeholder(tf.uint8, [None, None, None], 'image_x')
to_png = tf.image.encode_png(image_x)
for x in trange(images.shape[0], desc='PNG Encoding', leave=False):
raw.append(sess.run(to_png, feed_dict={image_x: images[x]}))
return raw
def _load_cifar10():
def unflatten(images):
return np.transpose(images.reshape((images.shape[0], 3, 32, 32)),
[0, 2, 3, 1])
with tempfile.NamedTemporaryFile() as f:
request.urlretrieve(URLS['cifar10'], f.name)
tar = tarfile.open(fileobj=f)
train_data_batches, train_data_labels = [], []
for batch in range(1, 6):
data_dict = scipy.io.loadmat(tar.extractfile(
'cifar-10-batches-mat/data_batch_{}.mat'.format(batch)))
train_data_batches.append(data_dict['data'])
train_data_labels.append(data_dict['labels'].flatten())
train_set = {'images': np.concatenate(train_data_batches, axis=0),
'labels': np.concatenate(train_data_labels, axis=0)}
data_dict = scipy.io.loadmat(tar.extractfile(
'cifar-10-batches-mat/test_batch.mat'))
test_set = {'images': data_dict['data'],
'labels': data_dict['labels'].flatten()}
train_set['images'] = _encode_png(unflatten(train_set['images']))
test_set['images'] = _encode_png(unflatten(test_set['images']))
return dict(train=train_set, test=test_set) | null |
162,064 | import collections
import gzip
import os
import sys
import tarfile
import tempfile
from urllib import request
from easydict import EasyDict
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
URLS = {
'svhn': 'http://ufldl.stanford.edu/housenumbers/{}_32x32.mat',
'cifar10': 'https://www.cs.toronto.edu/~kriz/cifar-10-matlab.tar.gz',
'cifar100': 'https://www.cs.toronto.edu/~kriz/cifar-100-matlab.tar.gz',
'stl10': 'http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz',
}
def _encode_png(images):
raw = []
with tf.Session() as sess, tf.device('cpu:0'):
image_x = tf.placeholder(tf.uint8, [None, None, None], 'image_x')
to_png = tf.image.encode_png(image_x)
for x in trange(images.shape[0], desc='PNG Encoding', leave=False):
raw.append(sess.run(to_png, feed_dict={image_x: images[x]}))
return raw
def _load_cifar100():
def unflatten(images):
return np.transpose(images.reshape((images.shape[0], 3, 32, 32)),
[0, 2, 3, 1])
with tempfile.NamedTemporaryFile() as f:
request.urlretrieve(URLS['cifar100'], f.name)
tar = tarfile.open(fileobj=f)
data_dict = scipy.io.loadmat(tar.extractfile('cifar-100-matlab/train.mat'))
train_set = {'images': data_dict['data'],
'labels': data_dict['fine_labels'].flatten()}
data_dict = scipy.io.loadmat(tar.extractfile('cifar-100-matlab/test.mat'))
test_set = {'images': data_dict['data'],
'labels': data_dict['fine_labels'].flatten()}
train_set['images'] = _encode_png(unflatten(train_set['images']))
test_set['images'] = _encode_png(unflatten(test_set['images']))
return dict(train=train_set, test=test_set) | null |
162,065 | import collections
import gzip
import os
import sys
import tarfile
import tempfile
from urllib import request
from easydict import EasyDict
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
DATA_DIR = os.environ['ML_DATA']
def _save_as_tfrecord(data, filename):
assert len(data['images']) == len(data['labels'])
filename = os.path.join(DATA_DIR, filename + '.tfrecord')
print('Saving dataset:', filename)
with tf.python_io.TFRecordWriter(filename) as writer:
for x in trange(len(data['images']), desc='Building records'):
feat = dict(image=_bytes_feature(data['images'][x]),
label=_int64_feature(data['labels'][x]))
record = tf.train.Example(features=tf.train.Features(feature=feat))
writer.write(record.SerializeToString())
print('Saved:', filename) | null |
162,066 | import collections
import gzip
import os
import sys
import tarfile
import tempfile
from urllib import request
from easydict import EasyDict
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
DATA_DIR = os.environ['ML_DATA']
def _is_installed(name, checksums):
for subset, checksum in checksums.items():
filename = os.path.join(DATA_DIR, '%s-%s.tfrecord' % (name, subset))
if not os.path.exists(filename):
return False
return True | null |
162,067 | import collections
import gzip
import os
import sys
import tarfile
import tempfile
from urllib import request
from easydict import EasyDict
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
DATA_DIR = os.environ['ML_DATA']
def _save_files(files, *args, **kwargs):
del args, kwargs
for folder in frozenset(os.path.dirname(x) for x in files):
os.makedirs(os.path.join(DATA_DIR, folder), exist_ok=True)
for filename, contents in files.items():
with open(os.path.join(DATA_DIR, filename), 'w') as f:
f.write(contents) | null |
162,068 | import collections
import gzip
import os
import sys
import tarfile
import tempfile
from urllib import request
from easydict import EasyDict
from libml.data import DATA_DIR
import numpy as np
import scipy.io
import tensorflow as tf
from tqdm import trange
DATA_DIR = os.environ['ML_DATA']
def _is_installed_folder(name, folder):
return os.path.exists(os.path.join(DATA_DIR, name, folder)) | null |
162,069 | from collections import defaultdict
import json
import os
from absl import app
from absl import flags
from libml import utils
from libml.data import DATA_DIR
import numpy as np
import tensorflow as tf
from tqdm import trange, tqdm
from typing import List, Any
def get_class(serialized_example):
return tf.parse_single_example(serialized_example, features={'label': tf.FixedLenFeature([], tf.int64)})['label'] | null |
162,070 | import hashlib
import itertools
import os
from absl import app
from absl import flags
from libml import data, utils
import tensorflow as tf
from tqdm import trange
FLAGS = flags.FLAGS
def to_byte(d: dict):
return tf.to_int32(tf.round(127.5 * (d['image'] + 1)))
def collect_hashes(sess, group, data):
data = data.map(to_byte).batch(FLAGS.batch).prefetch(1).make_one_shot_iterator().get_next()
hashes = set()
hasher = hashlib.sha512
for _ in trange(0, FLAGS.samples, FLAGS.batch, desc='Building hashes for %s' % group, leave=False):
try:
batch = sess.run(data)
except tf.errors.OutOfRangeError:
break
for img in batch:
hashes.add(hasher(img).digest())
return hashes | null |
162,071 | import glob
import json
import os.path
from absl import app
from absl import flags
import numpy as np
import tensorflow as tf
def summary_dict(accuracies):
return {
'last%02d' % x: np.median(accuracies[-x:]) for x in [1, 10, 20, 50]
} | null |
162,072 | import tornado.web
from consoleme.config import config
from consoleme.handlers.base import BaseHandler
from consoleme.lib.loader import WebpackLoader
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.models import DataTableResponse
async def _get_bundle(name, extension, config):
loader = WebpackLoader(name=name, config=config)
bundle = loader.get_bundle(name)
if extension:
bundle = await _filter_by_extension(bundle, extension)
return bundle
The provided code snippet includes necessary dependencies for implementing the `get_as_tags` function. Write a Python function `async def get_as_tags(name="main", extension=None, config=config, attrs="")` to solve the following problem:
Get a list of formatted <script> & <link> tags for the assets in the named bundle. :param bundle_name: The name of the bundle :param extension: (optional) filter by extension, eg. 'js' or 'css' :param config: (optional) the name of the configuration :return: a list of formatted tags as strings
Here is the function:
async def get_as_tags(name="main", extension=None, config=config, attrs=""):
"""
Get a list of formatted <script> & <link> tags for the assets in the
named bundle.
:param bundle_name: The name of the bundle
:param extension: (optional) filter by extension, eg. 'js' or 'css'
:param config: (optional) the name of the configuration
:return: a list of formatted tags as strings
"""
bundle = await _get_bundle(name, extension, config)
tags = []
for chunk in bundle:
if chunk["name"].endswith((".js", ".js.gz")):
tags.append(
('<script type="text/javascript" src="{0}" {1}></script>').format(
chunk["url"], attrs
)
)
elif chunk["name"].endswith((".css", ".css.gz")):
tags.append(
('<link type="text/css" href="{0}" rel="stylesheet" {1}/>').format(
chunk["url"], attrs
)
)
return tags | Get a list of formatted <script> & <link> tags for the assets in the named bundle. :param bundle_name: The name of the bundle :param extension: (optional) filter by extension, eg. 'js' or 'css' :param config: (optional) the name of the configuration :return: a list of formatted tags as strings |
162,073 | import sys
from consoleme.config import config
from consoleme.handlers.base import BaseMtlsHandler
from consoleme.lib.cloud_credential_authorization_mapping import (
CredentialAuthorizationMapping,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.models import Status2, WebResponse
def _get_last_page(total: int, page_size: int) -> int:
pages = int(total / page_size)
if not total % page_size:
pages += 1
return pages | null |
162,074 | import re
from typing import Dict, List, Optional
import ujson as json
from policyuniverse.expander_minimizer import _expand_wildcard_action
from consoleme.config import config
from consoleme.exceptions.exceptions import InvalidRequestParameter, MustBeFte
from consoleme.handlers.base import BaseAPIV1Handler, BaseHandler, BaseMtlsHandler
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.cache import retrieve_json_data_from_redis_or_s3
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.redis import redis_get, redis_hgetall
async def filter_resources(filter, resources, max=20):
if filter:
regexp = re.compile(r"{}".format(filter.strip()), re.IGNORECASE)
results: List[str] = []
for resource in resources:
try:
if regexp.search(str(resource.get(filter))):
if len(results) == max:
return results
results.append(resource)
except re.error:
# Regex error. Return no results
pass
return results
else:
return resources | null |
162,075 | import re
from typing import Dict, List, Optional
import ujson as json
from policyuniverse.expander_minimizer import _expand_wildcard_action
from consoleme.config import config
from consoleme.exceptions.exceptions import InvalidRequestParameter, MustBeFte
from consoleme.handlers.base import BaseAPIV1Handler, BaseHandler, BaseMtlsHandler
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.cache import retrieve_json_data_from_redis_or_s3
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.redis import redis_get, redis_hgetall
class InvalidRequestParameter(BaseException):
def __init__(self, msg=""):
async def get_account_id_to_name_mapping(
status="active", environment=None, force_sync=False
):
async def retrieve_json_data_from_redis_or_s3(
redis_key: str = None,
redis_data_type: str = "str",
s3_bucket: str = None,
s3_key: str = None,
cache_to_redis_if_data_in_s3: bool = True,
max_age: Optional[int] = None,
default: Optional = None,
json_object_hook: Optional = None,
json_encoder: Optional = None,
):
async def redis_get(key: str, default: Optional[str] = None) -> Optional[str]:
async def redis_hgetall(key: str, default=None):
async def handle_resource_type_ahead_request(cls):
try:
search_string: str = cls.request.arguments.get("search")[0].decode("utf-8")
except TypeError:
cls.send_error(400, message="`search` parameter must be defined")
return
try:
resource_type: str = cls.request.arguments.get("resource")[0].decode("utf-8")
except TypeError:
cls.send_error(400, message="`resource_type` parameter must be defined")
return
account_id = None
topic_is_hash = True
account_id_optional: Optional[List[bytes]] = cls.request.arguments.get("account_id")
if account_id_optional:
account_id = account_id_optional[0].decode("utf-8")
limit: int = 10
limit_optional: Optional[List[bytes]] = cls.request.arguments.get("limit")
if limit_optional:
limit = int(limit_optional[0].decode("utf-8"))
# By default, we only return the S3 bucket name of a resource and not the full ARN
# unless you specifically request it
show_full_arn_for_s3_buckets: Optional[bool] = cls.request.arguments.get(
"show_full_arn_for_s3_buckets"
)
role_name = False
if resource_type == "s3":
topic = config.get("redis.s3_bucket_key", "S3_BUCKETS")
s3_bucket = config.get("account_resource_cache.s3_combined.bucket")
s3_key = config.get(
"account_resource_cache.s3_combined.file",
"account_resource_cache/cache_s3_combined_v1.json.gz",
)
elif resource_type == "sqs":
topic = config.get("redis.sqs_queues_key", "SQS_QUEUES")
s3_bucket = config.get("account_resource_cache.sqs_combined.bucket")
s3_key = config.get(
"account_resource_cache.sqs_combined.file",
"account_resource_cache/cache_sqs_queues_combined_v1.json.gz",
)
elif resource_type == "sns":
topic = config.get("redis.sns_topics_key ", "SNS_TOPICS")
s3_bucket = config.get("account_resource_cache.sns_topics_combined.bucket")
s3_key = config.get(
"account_resource_cache.sns_topics_topics_combined.file",
"account_resource_cache/cache_sns_topics_combined_v1.json.gz",
)
elif resource_type == "iam_arn":
topic = config.get("aws.iamroles_redis_key ", "IAM_ROLE_CACHE")
s3_bucket = config.get(
"cache_iam_resources_across_accounts.all_roles_combined.s3.bucket"
)
s3_key = config.get(
"cache_iam_resources_across_accounts.all_roles_combined.s3.file",
"account_resource_cache/cache_all_roles_v1.json.gz",
)
elif resource_type == "iam_role":
topic = config.get("aws.iamroles_redis_key ", "IAM_ROLE_CACHE")
s3_bucket = config.get(
"cache_iam_resources_across_accounts.all_roles_combined.s3.bucket"
)
s3_key = config.get(
"cache_iam_resources_across_accounts.all_roles_combined.s3.file",
"account_resource_cache/cache_all_roles_v1.json.gz",
)
role_name = True
elif resource_type == "account":
topic = None
s3_bucket = None
s3_key = None
topic_is_hash = False
elif resource_type == "app":
topic = config.get("celery.apps_to_roles.redis_key", "APPS_TO_ROLES")
s3_bucket = None
s3_key = None
topic_is_hash = False
else:
cls.send_error(404, message=f"Invalid resource_type: {resource_type}")
return
if not topic and resource_type != "account":
raise InvalidRequestParameter("Invalid resource_type specified")
if topic and topic_is_hash and s3_key:
data = await retrieve_json_data_from_redis_or_s3(
redis_key=topic, redis_data_type="hash", s3_bucket=s3_bucket, s3_key=s3_key
)
elif topic:
data = await redis_get(topic)
results: List[Dict] = []
unique_roles: List[str] = []
if resource_type == "account":
account_and_id_list = []
account_ids_to_names = await get_account_id_to_name_mapping()
for account_id, account_name in account_ids_to_names.items():
account_and_id_list.append(f"{account_name} ({account_id})")
for account in account_and_id_list:
if search_string.lower() in account.lower():
results.append({"title": account})
elif resource_type == "app":
results = {}
all_role_arns = []
all_role_arns_j = await redis_hgetall(
(config.get("aws.iamroles_redis_key", "IAM_ROLE_CACHE"))
)
if all_role_arns_j:
all_role_arns = all_role_arns_j.keys()
# ConsoleMe (Account: Test, Arn: arn)
# TODO: Make this OSS compatible and configurable
try:
accounts = await get_account_id_to_name_mapping()
except Exception as e: # noqa
accounts = {}
app_to_role_map = {}
if data:
app_to_role_map = json.loads(data)
seen: Dict = {}
seen_roles = {}
for app_name, roles in app_to_role_map.items():
if len(results.keys()) > 9:
break
if search_string.lower() in app_name.lower():
results[app_name] = {"name": app_name, "results": []}
for role in roles:
account_id = role.split(":")[4]
account = accounts.get(account_id, "")
parsed_app_name = (
f"{app_name} on {account} ({account_id}) ({role})]"
)
if seen.get(parsed_app_name):
continue
seen[parsed_app_name] = True
seen_roles[role] = True
results[app_name]["results"].append(
{"title": role, "description": account}
)
for role in all_role_arns:
if len(results.keys()) > 9:
break
if search_string.lower() in role.lower():
if seen_roles.get(role):
continue
account_id = role.split(":")[4]
account = accounts.get(account_id, "")
if not results.get("Unknown App"):
results["Unknown App"] = {"name": "Unknown App", "results": []}
results["Unknown App"]["results"].append(
{"title": role, "description": account}
)
else:
if not data:
return []
for k, v in data.items():
if account_id and k != account_id:
continue
if role_name:
try:
r = k.split("role/")[1]
except IndexError:
continue
if search_string.lower() in r.lower():
if r not in unique_roles:
unique_roles.append(r)
results.append({"title": r})
elif resource_type == "iam_arn":
if k.startswith("arn:") and search_string.lower() in k.lower():
results.append({"title": k})
else:
list_of_items = json.loads(v)
for item in list_of_items:
# A Hack to get S3 to show full ARN, and maintain backwards compatibility
# TODO: Fix this in V2 of resource specific typeahead endpoints
if resource_type == "s3" and show_full_arn_for_s3_buckets:
item = f"arn:aws:s3:::{item}"
if search_string.lower() in item.lower():
results.append({"title": item, "account_id": k})
if len(results) > limit:
break
if len(results) > limit:
break
return results | null |
162,076 | import getpass
import platform
import click
import click_log
import ujson as json
from asgiref.sync import async_to_sync
from consoleme.lib.role_updater.handler import log
from consoleme.lib.role_updater.handler import update_role as update_role_handler
log = config.get_logger()
def cli():
log.debug("Running...")
print("RUNNING") | null |
162,077 | import getpass
import platform
import click
import click_log
import ujson as json
from asgiref.sync import async_to_sync
from consoleme.lib.role_updater.handler import log
from consoleme.lib.role_updater.handler import update_role as update_role_handler
def get_session_name():
"""Set a session name if running locally."""
if platform.platform().lower().startswith("darwin"):
session_name = getpass.getuser()
return session_name
return "roleupdater"
log = config.get_logger()
The provided code snippet includes necessary dependencies for implementing the `update_role` function. Write a Python function `def update_role(event)` to solve the following problem:
Update a role policy
Here is the function:
def update_role(event):
"""Update a role policy"""
with open(event, "r") as f:
event_data = json.load(f)
for e in event_data:
e["requestor"] = e["requestor"].format(requestor=get_session_name())
result = async_to_sync(update_role_handler)(event_data, None)
if result.get("success", False):
log.info("Role policy update successful")
else:
log.info("Role policy update failed") | Update a role policy |
162,078 | from datetime import datetime, timedelta
from typing import List, Optional, Union
import ujson as json
from asgiref.sync import sync_to_async
from policy_sentry.util.arns import parse_arn
from consoleme.config import config
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.policies import get_aws_config_history_url_for_resource
from consoleme.lib.redis import RedisHandler, redis_get
from consoleme.models import (
AwsPrincipalModel,
CloudTrailDetailsModel,
CloudTrailError,
CloudTrailErrorArray,
EligibleRolesModel,
EligibleRolesModelArray,
ExtendedAwsPrincipalModel,
S3DetailsModel,
S3Error,
S3ErrorArray,
)
async def get_app_details_for_role(arn: str):
"""
Retrieves applications associated with role, if they exist
:param arn:
:return:
"""
return await internal_policies.get_applications_associated_with_role(arn)
async def get_account_id_to_name_mapping(
status="active", environment=None, force_sync=False
):
redis_key = config.get(
"cache_cloud_accounts.redis.key.all_accounts_key", "ALL_AWS_ACCOUNTS"
)
accounts = await retrieve_json_data_from_redis_or_s3(redis_key, default={})
if force_sync or not accounts or not accounts.get("accounts"):
# Force a re-sync and then retry
await cache_cloud_accounts()
accounts = await retrieve_json_data_from_redis_or_s3(
redis_key,
s3_bucket=config.get("cache_cloud_accounts.s3.bucket"),
s3_key=config.get(
"cache_cloud_accounts.s3.file",
"cache_cloud_accounts/accounts_v1.json.gz",
),
default={},
)
account_id_to_name = {}
for account in accounts.get("accounts", []):
if status and account.get("status") != status:
continue
if environment and account.get("environment") != environment:
continue
account_id_to_name[account["id"]] = account["name"]
return account_id_to_name
class EligibleRolesModel(BaseModel):
arn: str = Field(..., description="ARN of the role")
account_id: str = Field(..., description="Account ID of the role")
account_friendly_name: Optional[str] = Field(
None, description='Account\'s friendly name (if known), otherwise "Unknown"'
)
role_name: str = Field(..., description="Name of the role")
apps: Optional[AppDetailsArray] = None
class EligibleRolesModelArray(BaseModel):
roles: Optional[List[EligibleRolesModel]] = None
async def get_eligible_role_details(
eligible_roles: List[str],
) -> EligibleRolesModelArray:
account_ids_to_name = await get_account_id_to_name_mapping()
eligible_roles_detailed = []
for role in eligible_roles:
arn_parsed = parse_arn(role)
account_id = arn_parsed["account"]
role_name = (
arn_parsed["resource_path"]
if arn_parsed["resource_path"]
else arn_parsed["resource"]
)
account_friendly_name = account_ids_to_name.get(account_id, "Unknown")
role_apps = await get_app_details_for_role(role)
eligible_roles_detailed.append(
EligibleRolesModel(
arn=role,
account_id=account_id,
account_friendly_name=account_friendly_name,
role_name=role_name,
apps=role_apps,
)
)
return EligibleRolesModelArray(roles=eligible_roles_detailed) | null |
162,079 | import json as original_json
import sys
import time
from collections import defaultdict
from typing import Dict
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.cache import (
retrieve_json_data_from_redis_or_s3,
store_json_results_in_redis_and_s3,
)
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.json_encoder import SetEncoder
from consoleme.lib.notifications.models import (
ConsoleMeUserNotification,
GetNotificationsForUserResponse,
)
from consoleme.lib.singleton import Singleton
log = config.get_logger()
class RetrieveNotifications(metaclass=Singleton):
def __init__(self):
self.last_update = 0
self.all_notifications = []
async def retrieve_all_notifications(self, force_refresh=False):
if force_refresh or (
int(time.time()) - self.last_update
> config.get(
"get_notifications_for_user.notification_retrieval_interval", 20
)
):
self.all_notifications = await retrieve_json_data_from_redis_or_s3(
redis_key=config.get("notifications.redis_key", "ALL_NOTIFICATIONS"),
redis_data_type="hash",
s3_bucket=config.get("notifications.s3.bucket"),
s3_key=config.get(
"notifications.s3.key", "notifications/all_notifications_v1.json.gz"
),
default={},
)
self.last_update = int(time.time())
return self.all_notifications
class ConsoleMeUserNotification(BaseModel):
predictable_id: str = Field(
...,
description=(
"Predictable ID for this notification. Generally used to prevent duplicate notifications"
),
)
type: str = Field(
...,
description=(
"Each class of notification should be given a separate type, "
"IE: `cloudtrail_generated_policy` or `proxy_generated_policy"
),
)
users_or_groups: Set[str] = Field(
..., description="Users or groups who should see the notification"
)
event_time: int = Field(..., description="Time that the event took place")
expiration: int = Field(
..., description="Time that this entry should stop notifying people"
)
expired: bool = Field(
...,
description="A more obvious indicator about whether a notification has expired",
)
header: Optional[str] = Field(
None, description="Bolded text (Header) for the notification"
)
message: str = Field(
...,
description="An (optionally markdown) formatted message to show to users in the UI",
)
message_actions: List[ConsoleMeUserNotificationAction] = Field(
...,
description=(
"An optional list of actions to make available to the user. These will be shown below the notification."
),
)
details: Dict[str, Any] = Field(
...,
description=(
"Extra details about the notification for power users. "
"This will be accessible to the user in the UI, but not visible by default"
),
)
read_by_users: List[str] = Field(
...,
description=(
"List of users the notification is `read` for. It will show up in the user's list of notifications, "
"but will not be shown as `unread` nor be included in the unread counter."
),
)
read_by_all: bool = Field(
False,
description=(
"Notification is `marked as read` for all users and will not appear as an unread notification for "
"any users."
),
)
hidden_for_users: List[str] = Field(
...,
description=(
"List of users the notification is `hidden` for. It will not appear at all in the user's list of "
"notifications."
),
)
hidden_for_all: bool = Field(
False,
description=(
"Notification is `marked as hidden` for all users, and will not appear in the notificaiton list for "
"any user."
),
)
read_for_current_user: bool = Field(
None,
description=(
"Convenience variable to mark a notification as read for current user when retrieving notification. "
"This makes it so the frontend doesn't need to do any computation to figure it out. A Non-None value "
"should not be stored in the database."
),
)
version: int = Field(..., description=("Version of the notification model"))
class GetNotificationsForUserResponse(BaseModel):
notifications: List[ConsoleMeUserNotification]
unread_count: int
async def get_notifications_for_user(
user,
groups,
max_notifications=config.get("get_notifications_for_user.max_notifications", 5),
force_refresh=False,
) -> GetNotificationsForUserResponse:
function = f"{__name__}.{sys._getframe().f_code.co_name}"
log_data = {
"function": function,
"user": user,
"max_notifications": max_notifications,
"force_refresh": force_refresh,
}
current_time = int(time.time())
all_notifications = await RetrieveNotifications().retrieve_all_notifications(
force_refresh
)
unread_count = 0
notifications_for_user = []
for user_or_group in [user, *groups]:
# Filter out identical notifications that were already captured via user-specific attribution. IE: "UserA"
# performed an access deny operation locally under "RoleA" with session name = "UserA", so the generated
# notification is tied to the user. However, "UserA" is a member of "GroupA", which owns RoleA. We want
# to show the notification to members of "GroupA", as well as "UserA" but we don't want "UserA" to see 2
# notifications.
notifications = all_notifications.get(user_or_group)
if not notifications:
continue
notifications = json.loads(notifications)
for notification_raw in notifications:
try:
# We parse ConsoleMeUserNotification individually instead of as an array
# to account for future changes to the model that may invalidate older
# notifications
notification = ConsoleMeUserNotification.parse_obj(notification_raw)
except Exception as e:
log.error({**log_data, "error": str(e)})
sentry_sdk.capture_exception()
continue
if notification.version != 1:
# Skip unsupported versions of the notification model
continue
if user in notification.hidden_for_users:
# Skip this notification if it isn't hidden for the user
continue
seen = False
for existing_user_notification_raw in notifications_for_user:
existing_user_notification = ConsoleMeUserNotification.parse_obj(
existing_user_notification_raw
)
if (
notification.predictable_id
== existing_user_notification.predictable_id
):
seen = True
if not seen:
notifications_for_user.append(notification)
# Filter out "expired" notifications
notifications_for_user = [
v for v in notifications_for_user if v.expiration > current_time
]
# Show newest notifications first
notifications_for_user = sorted(
notifications_for_user, key=lambda i: i.event_time, reverse=True
)
# Increment Unread Count
notifications_to_return = notifications_for_user[0:max_notifications]
for notification in notifications_to_return:
if user in notification.read_by_users or notification.read_by_all:
notification.read_for_current_user = True
continue
unread_count += 1
return GetNotificationsForUserResponse(
notifications=notifications_to_return, unread_count=unread_count
) | null |
162,080 | import json as original_json
import sys
import time
from collections import defaultdict
from typing import Dict
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.cache import (
retrieve_json_data_from_redis_or_s3,
store_json_results_in_redis_and_s3,
)
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.json_encoder import SetEncoder
from consoleme.lib.notifications.models import (
ConsoleMeUserNotification,
GetNotificationsForUserResponse,
)
from consoleme.lib.singleton import Singleton
class UserDynamoHandler(BaseDynamoHandler):
def __init__(self, user_email: Optional[str] = None) -> None:
try:
self.requests_table = self._get_dynamo_table(
config.get("aws.requests_dynamo_table", "consoleme_requests_global")
)
self.users_table = self._get_dynamo_table(
config.get("aws.users_dynamo_table", "consoleme_users_global")
)
self.group_log = self._get_dynamo_table(
config.get("aws.group_log_dynamo_table", "consoleme_audit_global")
)
self.dynamic_config = self._get_dynamo_table(
config.get("aws.group_log_dynamo_table", "consoleme_config_global")
)
self.policy_requests_table = self._get_dynamo_table(
config.get(
"aws.policy_requests_dynamo_table", "consoleme_policy_requests"
)
)
self.api_health_roles_table = self._get_dynamo_table(
config.get(
"aws.api_health_apps_table_dynamo_table",
"consoleme_api_health_apps",
)
)
self.resource_cache_table = self._get_dynamo_table(
config.get(
"aws.resource_cache_dynamo_table", "consoleme_resource_cache"
)
)
self.cloudtrail_table = self._get_dynamo_table(
config.get("aws.cloudtrail_table", "consoleme_cloudtrail")
)
self.notifications_table = self._get_dynamo_table(
config.get("aws.notifications_table", "consoleme_notifications")
)
if user_email:
self.user = self.get_or_create_user(user_email)
self.affected_user = self.user
except Exception:
if config.get("development"):
log.error(
"Unable to connect to Dynamo. Trying to set user via development configuration",
exc_info=True,
)
self.user = self.sign_request(
{
"last_updated": int(time.time()),
"username": user_email,
"requests": [],
}
)
self.affected_user = self.user
else:
log.error("Unable to get Dynamo table.", exc_info=True)
raise
def write_resource_cache_data(self, data):
self.parallel_write_table(
self.resource_cache_table, data, ["resourceId", "resourceType"]
)
async def get_dynamic_config_yaml(self) -> bytes:
"""Retrieve dynamic configuration yaml."""
return await sync_to_async(self.get_dynamic_config_yaml_sync)()
def get_dynamic_config_yaml_sync(self) -> bytes:
"""Retrieve dynamic configuration yaml synchronously"""
c = b""
try:
current_config = self.dynamic_config.get_item(Key={"id": "master"})
if not current_config:
return c
compressed_config = current_config.get("Item", {}).get("config", "")
if not compressed_config:
return c
c = zlib.decompress(compressed_config.value)
except Exception: # noqa
sentry_sdk.capture_exception()
return c
def get_dynamic_config_dict(self) -> dict:
"""Retrieve dynamic configuration dictionary that can be merged with primary configuration dictionary."""
try:
loop = asyncio.get_running_loop()
except RuntimeError: # if cleanup: 'RuntimeError: There is no current event loop..'
loop = None
if loop and loop.is_running():
current_config_yaml = self.get_dynamic_config_yaml_sync()
else:
current_config_yaml = asyncio.run(self.get_dynamic_config_yaml())
config_d = yaml.safe_load(current_config_yaml)
return config_d
async def get_all_api_health_alerts(self) -> list:
"""Return all requests. If a status is specified, only requests with the specified status will be returned.
:param status:
:return:
"""
response: dict = self.api_health_roles_table.scan()
items = response.get("Items", [])
while "LastEvaluatedKey" in response:
response = self.api_health_roles_table.scan(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def get_api_health_alert_app(self, app_name) -> dict:
resp: dict = await sync_to_async(self.api_health_roles_table.get_item)(
Key={"appName": app_name}
)
return resp.get("Item", None)
async def write_api_health_alert_info(self, request, user_email: str):
"""
Writes a health alert role to the appropriate DynamoDB table
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
# enrich request
request["app_create_time"]: int = int(time.time())
request["updated_by"]: str = user_email
request["last_updated"]: int = int(time.time())
try:
await sync_to_async(self.api_health_roles_table.put_item)(
Item=self._data_to_dynamo_replace(request)
)
except Exception:
error = {
"message": "Unable to add new api_health info request",
"request": request,
"function": function,
}
log.error(error, exc_info=True)
raise
return request
async def update_api_health_alert_info(
self, request: dict, user_email=None, update_by=None, last_updated=None
):
"""
Update api_health_alert_info by roleName
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
# enrich request
if update_by:
request["updated_by"] = update_by
else:
request["updated_by"] = user_email
if last_updated:
request["last_updated"] = last_updated
else:
request["last_updated"] = int(time.time())
try:
await sync_to_async(self.api_health_roles_table.put_item)(
Item=self._data_to_dynamo_replace(request)
)
except Exception as e:
error: dict = {
"function": function,
"message": "Unable to update api_health_info request",
"request": request,
"error": str(e),
}
log.error(error, exc_info=True)
raise Exception(error)
return request
async def delete_api_health_alert_info(self, app: str) -> None:
"""
Delete api_health_alert_info by roleName
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
try:
await sync_to_async(self.api_health_roles_table.delete_item)(
Key={"appName": app}
)
except Exception:
error: dict = {
"function": function,
"message": "Unable to delete api_health info",
"app": app,
}
log.error(error, exc_info=True)
raise
async def write_policy_request(
self,
user_email: str,
justification: str,
arn: str,
policy_name: str,
policy_changes: dict,
resources: List[str],
resource_policies: List[Dict],
request_time: int = None,
request_uuid=None,
policy_status="pending",
cross_account_request: bool = False,
dry_run: bool = False,
):
"""
Writes a policy request to the appropriate DynamoDB table
dry_run will create the request format, but won't actually write it
Sample run:
write_policy_request(policy_changes)
"""
request_time = request_time or int(time.time())
# Craft the new request json
timestamp = int(time.time())
request_id = request_uuid or str(uuid.uuid4())
new_request = {
"request_id": request_id,
"arn": arn,
"status": policy_status,
"justification": justification,
"request_time": request_time,
"updated_by": user_email,
"last_updated": timestamp,
"username": user_email,
"policy_name": policy_name,
"policy_changes": json.dumps(policy_changes),
"resources": resources,
"resource_policies": resource_policies,
"cross_account_request": cross_account_request,
}
if not dry_run:
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(new_request)
)
except Exception as e:
error = f"Unable to add new policy request: {new_request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
else:
log_data = {
"function": f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}",
"request": new_request,
"message": "Dry run, skipping adding request to dynamo",
}
log.debug(log_data)
return new_request
async def write_policy_request_v2(self, extended_request: ExtendedRequestModel):
"""
Writes a policy request v2 to the appropriate DynamoDB table
Sample run:
write_policy_request_v2(request)
"""
new_request = {
"request_id": extended_request.id,
"principal": extended_request.principal.dict(),
"status": extended_request.request_status.value,
"justification": extended_request.justification,
"request_time": extended_request.timestamp,
"last_updated": int(time.time()),
"version": "2",
"extended_request": json.loads(extended_request.json()),
"username": extended_request.requester_email,
}
if extended_request.principal.principal_type == "AwsResource":
new_request["arn"] = extended_request.principal.principal_arn
elif extended_request.principal.principal_type == "HoneybeeAwsResourceTemplate":
repository_name = extended_request.principal.repository_name
resource_identifier = extended_request.principal.resource_identifier
new_request["arn"] = f"{repository_name}-{resource_identifier}"
else:
raise Exception("Invalid principal type")
log_data = {
"function": f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}",
"message": "Writing policy request v2 to Dynamo",
"request": new_request,
}
log.debug(log_data)
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(new_request)
)
log_data[
"message"
] = "Successfully finished writing policy request v2 to Dynamo"
log.debug(log_data)
except Exception as e:
log_data["message"] = "Error occurred writing policy request v2 to Dynamo"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
error = f"{log_data['message']}: {str(e)}"
raise Exception(error)
return new_request
async def update_policy_request(self, updated_request):
"""
Update a policy request by request ID
Sample run:
update_policy_request(policy_changes)
"""
updated_request["last_updated"] = int(time.time())
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(updated_request)
)
except Exception as e:
error = f"Unable to add updated policy request: {updated_request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return updated_request
async def get_policy_requests(self, arn=None, request_id=None):
"""Reads a policy request from the appropriate DynamoDB table"""
if not arn and not request_id:
raise Exception("Must pass in ARN or policy request ID")
if request_id:
requests = self.policy_requests_table.query(
KeyConditionExpression="request_id = :ri",
ExpressionAttributeValues={":ri": request_id},
)
else:
requests = self.policy_requests_table.query(
KeyConditionExpression="arn = :arn",
ExpressionAttributeValues={":arn": arn},
)
matching_requests = []
if requests["Items"]:
items = self._data_from_dynamo_replace(requests["Items"])
items = await self.convert_policy_requests_to_v3(items)
matching_requests.extend(items)
return matching_requests
async def convert_policy_requests_to_v3(self, requests):
# Remove this function and calls to this function after a grace period of
changed = False
for request in requests:
if not request.get("version") in ["2"]:
continue
if request.get("extended_request") and not request.get("principal"):
principal_arn = request.pop("arn")
request["principal"] = {
"principal_arn": principal_arn,
"principal_type": "AwsResource",
}
request["extended_request"]["principal"] = {
"principal_arn": principal_arn,
"principal_type": "AwsResource",
}
request.pop("arn", None)
changes = (
request.get("extended_request", {})
.get("changes", {})
.get("changes", [])
)
for change in changes:
if not change.get("principal_arn"):
continue
if not change.get("version") in ["2.0", "2", 2]:
continue
change["principal"] = {
"principal_arn": change["principal_arn"],
"principal_type": "AwsResource",
}
change.pop("principal_arn")
change["version"] = "3.0"
changed = True
if changed:
self.parallel_write_table(self.policy_requests_table, requests)
return requests
async def get_all_policy_requests(
self, status: Optional[str] = "pending"
) -> List[Dict[str, Union[int, List[str], str]]]:
"""Return all policy requests. If a status is specified, only requests with the specified status will be
returned.
:param status:
:return:
"""
requests = await sync_to_async(self.parallel_scan_table)(
self.policy_requests_table
)
requests = await self.convert_policy_requests_to_v3(requests)
return_value = []
if status:
for item in requests:
if status and item["status"] == status:
return_value.append(item)
else:
return_value = requests
return return_value
async def update_dynamic_config(self, config: str, updated_by: str) -> None:
"""Take a YAML config and writes to DDB (The reason we use YAML instead of JSON is to preserve comments)."""
# Validate that config loads as yaml, raises exception if not
yaml.safe_load(config)
stats.count("update_dynamic_config", tags={"updated_by": updated_by})
current_config_entry = self.dynamic_config.get_item(Key={"id": "master"})
if current_config_entry.get("Item"):
old_config = {
"id": current_config_entry["Item"]["updated_at"],
"updated_by": current_config_entry["Item"]["updated_by"],
"config": current_config_entry["Item"]["config"],
"updated_at": str(int(time.time())),
}
self.dynamic_config.put_item(Item=self._data_to_dynamo_replace(old_config))
new_config = {
"id": "master",
"config": zlib.compress(config.encode()),
"updated_by": updated_by,
"updated_at": str(int(time.time())),
}
self.dynamic_config.put_item(Item=self._data_to_dynamo_replace(new_config))
def validate_signature(self, items):
signature = items.pop("signature")
if isinstance(signature, Binary):
signature = signature.value
json_request = json.dumps(items, sort_keys=True)
if not crypto.verify(json_request, signature):
raise Exception(f"Invalid signature for request: {json_request}")
def sign_request(
self, user_entry: Dict[str, Union[Decimal, List[str], Binary, str]]
) -> Dict[str, Union[Decimal, List[str], str, bytes]]:
"""
Sign the request and returned request with signature
:param user_entry:
:return:
"""
# Remove old signature if it exists
user_entry.pop("signature", None)
user_entry = self._data_from_dynamo_replace(user_entry)
json_request = json.dumps(user_entry, sort_keys=True, use_decimal=True)
sig = crypto.sign(json_request)
user_entry["signature"] = sig
return user_entry
async def authenticate_user(self, login_attempt) -> AuthenticationResponse:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {
"function": function,
"user_email": login_attempt.username,
"after_redirect_uri": login_attempt.after_redirect_uri,
}
user_entry = await sync_to_async(self.users_table.query)(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": login_attempt.username},
)
user = None
generic_error = ["User doesn't exist, or password is incorrect. "]
if user_entry and "Items" in user_entry and len(user_entry["Items"]) == 1:
user = user_entry["Items"][0]
if not user:
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = f"Unable to find user: {login_attempt.username}"
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
if not user.get("password"):
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = "User exists, but doesn't have a password stored in the database"
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
password_hash_matches = bcrypt.checkpw(
login_attempt.password.encode("utf-8"), user["password"].value
)
if not password_hash_matches:
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = "Password does not match. "
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
return AuthenticationResponse(
authenticated=True, username=user["username"], groups=user["groups"]
)
def create_user(
self,
user_email,
password: Optional[str] = None,
groups: Optional[List[str]] = None,
):
if not groups:
groups = []
timestamp = int(time.time())
unsigned_user_entry = {
"created": timestamp,
"last_updated": timestamp,
"username": user_email,
"requests": [],
"groups": groups,
}
if password:
pw = bytes(password, "utf-8")
salt = bcrypt.gensalt()
unsigned_user_entry["password"] = bcrypt.hashpw(pw, salt)
user_entry = self.sign_request(unsigned_user_entry)
try:
self.users_table.put_item(Item=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to add user submission: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return user_entry
def update_user(
self,
user_email,
password: Optional[str] = None,
groups: Optional[List[str]] = None,
):
if not groups:
groups = []
user_ddb = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
user = None
if user_ddb and "Items" in user_ddb and len(user_ddb["Items"]) == 1:
user = user_ddb["Items"][0]
if not user:
raise DataNotRetrievable(f"Unable to find user: {user_email}")
timestamp = int(time.time())
if password:
pw = bytes(password, "utf-8")
salt = bcrypt.gensalt()
user["password"] = bcrypt.hashpw(pw, salt)
if groups:
user["groups"] = groups
user["last_updated"] = timestamp
user_entry = self.sign_request(user)
try:
self.users_table.put_item(Item=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to add user submission: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return user_entry
def delete_user(self, user_email):
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user_entry = {"username": user_email}
try:
self.users_table.delete_item(Key=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to delete user: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
async def get_user(
self, user_email: str
) -> Optional[Dict[str, Union[Decimal, List[str], Binary, str]]]:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
if user and "Items" in user and len(user["Items"]) == 1:
return user["Items"][0]
return None
def get_or_create_user(
self, user_email: str
) -> Dict[str, Union[Decimal, List[str], Binary, str]]:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
items = []
if user and "Items" in user:
items = user["Items"]
if not items:
return self.create_user(user_email)
return items[0]
def resolve_request_ids(
self, request_ids: List[str]
) -> List[Dict[str, Union[int, str]]]:
requests = []
for request_id in request_ids:
request = self.requests_table.query(
KeyConditionExpression="request_id = :ri",
ExpressionAttributeValues={":ri": request_id},
)
if request["Items"]:
items = self._data_from_dynamo_replace(request["Items"])
requests.append(items[0])
else:
raise NoMatchingRequest(
f"No matching request for request_id: {request_id}"
)
return requests
def add_request_id_to_user(
self,
affected_user: Dict[str, Union[Decimal, List[str], Binary, str]],
request_id: str,
) -> None:
affected_user["requests"].append(request_id)
self.users_table.put_item(
Item=self._data_to_dynamo_replace(self.sign_request(affected_user))
)
def add_request(
self,
user_email: str,
group: str,
justification: str,
request_time: None = None,
status: str = "pending",
updated_by: Optional[str] = None,
) -> Dict[str, Union[int, str]]:
"""
Add a user request to the dynamo table
Sample run:
add_request("user@example.com", "engtest", "because")
:param user_email: Email address of user
:param group: Name of group user is requesting access to
:param justification:
:param request_id:
:param request_time:
:param status:
:param updated_by:
:return:
"""
"""
Request:
group
justification
role
request_time
approval_time
updated_by
approval_reason
status
user@example.com:
requests: []
last_updated: 1
signature: xxxx
#pending: []
#expired: []
# How to expire requests if soemeone maliciously deletes content
# How to query for all approved requests for group X
# What if we want to send email saying your request is expiring in 7 days? Maybe celery to query all
# What about concept of request ID? Maybe base64 encoded thing?
# Need an all-in-one page to show all pending requests, all expired/approved requests
"""
request_time = request_time or int(time.time())
stats.count("new_group_request", tags={"user": user_email, "group": group})
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
# Get current user. Create if they do not already exist
# self.user = self.get_or_create_user(user_email)
# Get current user requests, which will validate existing signature
# existing_request_ids = self.user["requests"]
# existing_requests = self.resolve_request_ids(existing_request_ids)
existing_pending_requests_for_group = self.get_requests_by_user(
user_email, group, status="pending"
)
# Craft the new request json
timestamp = int(time.time())
request_id = str(uuid.uuid4())
new_request = {
"request_id": request_id,
"group": group,
"status": status,
"justification": justification,
"request_time": request_time,
"updated_by": updated_by,
"last_updated": timestamp,
"username": user_email,
}
# See if user already has an active or pending request for the group
if existing_pending_requests_for_group:
for request in existing_pending_requests_for_group:
raise PendingRequestAlreadyExists(
f"Pending request for group: {group} already exists: {request}"
)
try:
self.requests_table.put_item(Item=self._data_to_dynamo_replace(new_request))
except Exception as e:
error = {
"error": f"Unable to add user request: {str(e)}",
"request": new_request,
}
log.error(error, exc_info=True)
raise Exception(error)
self.add_request_id_to_user(self.affected_user, request_id)
return new_request
async def get_all_requests(self, status=None):
"""Return all requests. If a status is specified, only requests with the specified status will be returned.
:param status:
:return:
"""
items = await sync_to_async(self.parallel_scan_table)(self.requests_table)
return_value = []
if status:
for item in items:
new_json = []
for j in item["json"]:
if j["status"] == status:
new_json.append(j)
item["json"] = new_json
if new_json:
return_value.append(item)
else:
return_value = items
return return_value
def get_requests_by_user(
self,
user_email: str,
group: str = None,
status: str = None,
use_cache: bool = False,
) -> dict:
"""Get requests by user. Group and status can also be specified to filter results.
:param user_email:
:param group:
:param status:
:return:
"""
red_key = f"USER_REQUESTS_{user_email}-{group}-{status}"
if use_cache:
requests_to_return = red.get(red_key)
if requests_to_return:
return json.loads(requests_to_return)
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
existing_request_ids = self.affected_user["requests"]
existing_requests = self.resolve_request_ids(existing_request_ids)
requests_to_return = []
if existing_requests:
for request in existing_requests:
if group and request["group"] != group:
continue
if status and request["status"] != status:
continue
requests_to_return.append(request)
if use_cache:
red.setex(red_key, 120, json.dumps(requests_to_return))
return requests_to_return
def change_request_status(
self, user_email, group, new_status, updated_by=None, reviewer_comments=None
):
"""
:param user:
:param status:
:param request_id:
:return:
"""
stats.count(
"update_group_request",
tags={
"user": user_email,
"group": group,
"new_status": new_status,
"updated_by": updated_by,
},
)
modified_request = None
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
timestamp = int(time.time())
if new_status not in POSSIBLE_STATUSES:
raise Exception(
f"Invalid status. Status must be one of {POSSIBLE_STATUSES}"
)
if new_status == "approved" and not updated_by:
raise Exception(
"You must provide `updated_by` to change a request status to approved."
)
existing_requests = self.get_requests_by_user(user_email)
if existing_requests:
updated = False
for request in existing_requests:
if request["group"] == group:
request["updated_by"] = updated_by
request["status"] = new_status
request["last_updated"] = timestamp
request["reviewer_comments"] = reviewer_comments
modified_request = request
try:
self.requests_table.put_item(
Item=self._data_to_dynamo_replace(request)
)
except Exception as e:
error = f"Unable to add user request: {request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
updated = True
if not updated:
raise NoExistingRequest(
f"Unable to find existing request for user: {user_email} and group: {group}."
)
else:
raise NoExistingRequest(
f"Unable to find existing requests for user: {user_email}"
)
return modified_request
def change_request_status_by_id(
self,
request_id: str,
new_status: str,
updated_by: Optional[str] = None,
reviewer_comments: Optional[str] = None,
) -> Dict[str, Union[int, str]]:
"""
Change request status by ID
:param request_id:
:param new_status:
:param updated_by:
:return: new requests
"""
modified_request = None
if new_status == "approved" and not updated_by:
raise Exception(
"You must provide `updated_by` to change a request status to approved."
)
requests = self.resolve_request_ids([request_id])
if new_status not in POSSIBLE_STATUSES:
raise Exception(
f"Invalid status. Status must be one of {POSSIBLE_STATUSES}"
)
for request in requests:
request["status"] = new_status
request["updated_by"] = updated_by
request["last_updated"] = int(time.time())
request["reviewer_comments"] = reviewer_comments
modified_request = request
try:
self.requests_table.put_item(Item=self._data_to_dynamo_replace(request))
except Exception as e:
error = f"Unable to add user request: {request} : {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return modified_request
def get_all_policies(self):
"""Return all policies."""
response = self.policies_table.scan()
items = []
if response and "Items" in response:
items = self._data_from_dynamo_replace(response["Items"])
while "LastEvaluatedKey" in response:
response = self.policies_table.scan(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def create_group_log_entry(
self,
group: str,
username: str,
updated_by: str,
action: str,
updated_at: None = None,
extra: None = None,
) -> None:
updated_at = updated_at or int(time.time())
log_id = str(uuid.uuid4())
log_entry = {
"uuid": log_id,
"group": group,
"username": username,
"updated_by": updated_by,
"updated_at": updated_at,
"action": action,
"extra": extra,
}
self.group_log.put_item(Item=self._data_to_dynamo_replace(log_entry))
async def get_all_audit_logs(self) -> List[Dict[str, Union[int, None, str]]]:
response = await sync_to_async(self.group_log.scan)()
items = []
if response and "Items" in response:
items = self._data_from_dynamo_replace(response["Items"])
while "LastEvaluatedKey" in response:
response = await sync_to_async(self.group_log.scan)(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def get_all_pending_requests(self):
return await self.get_all_requests(status="pending")
def batch_write_cloudtrail_events(self, items):
with self.cloudtrail_table.batch_writer(
overwrite_by_pkeys=["arn", "request_id"]
) as batch:
for item in items:
batch.put_item(Item=self._data_to_dynamo_replace(item))
return True
async def get_top_cloudtrail_errors_by_arn(self, arn, n=5):
response: dict = await sync_to_async(self.cloudtrail_table.query)(
KeyConditionExpression=Key("arn").eq(arn)
)
items = response.get("Items", [])
aggregated_errors = defaultdict(dict)
for item in items:
if int(item["ttl"]) < int(time.time()):
continue
event_call = item["event_call"]
event_resource = item.get("resource", "")
event_string = f"{event_call}|||{event_resource}"
if not aggregated_errors.get(event_string):
aggregated_errors[event_string]["count"] = 0
aggregated_errors[event_string]["generated_policy"] = item.get(
"generated_policy", {}
)
aggregated_errors[event_string]["count"] += 1
top_n_errors = {
k: v
for k, v in sorted(
aggregated_errors.items(),
key=lambda item: item[1]["count"],
reverse=True,
)[:n]
}
return top_n_errors
def count_arn_errors(self, error_count, items):
for item in items:
arn = item.get("arn")
if not error_count.get(arn):
error_count[arn] = 0
error_count[arn] += item.get("count", 1)
return error_count
class ConsoleMeUserNotification(BaseModel):
predictable_id: str = Field(
...,
description=(
"Predictable ID for this notification. Generally used to prevent duplicate notifications"
),
)
type: str = Field(
...,
description=(
"Each class of notification should be given a separate type, "
"IE: `cloudtrail_generated_policy` or `proxy_generated_policy"
),
)
users_or_groups: Set[str] = Field(
..., description="Users or groups who should see the notification"
)
event_time: int = Field(..., description="Time that the event took place")
expiration: int = Field(
..., description="Time that this entry should stop notifying people"
)
expired: bool = Field(
...,
description="A more obvious indicator about whether a notification has expired",
)
header: Optional[str] = Field(
None, description="Bolded text (Header) for the notification"
)
message: str = Field(
...,
description="An (optionally markdown) formatted message to show to users in the UI",
)
message_actions: List[ConsoleMeUserNotificationAction] = Field(
...,
description=(
"An optional list of actions to make available to the user. These will be shown below the notification."
),
)
details: Dict[str, Any] = Field(
...,
description=(
"Extra details about the notification for power users. "
"This will be accessible to the user in the UI, but not visible by default"
),
)
read_by_users: List[str] = Field(
...,
description=(
"List of users the notification is `read` for. It will show up in the user's list of notifications, "
"but will not be shown as `unread` nor be included in the unread counter."
),
)
read_by_all: bool = Field(
False,
description=(
"Notification is `marked as read` for all users and will not appear as an unread notification for "
"any users."
),
)
hidden_for_users: List[str] = Field(
...,
description=(
"List of users the notification is `hidden` for. It will not appear at all in the user's list of "
"notifications."
),
)
hidden_for_all: bool = Field(
False,
description=(
"Notification is `marked as hidden` for all users, and will not appear in the notificaiton list for "
"any user."
),
)
read_for_current_user: bool = Field(
None,
description=(
"Convenience variable to mark a notification as read for current user when retrieving notification. "
"This makes it so the frontend doesn't need to do any computation to figure it out. A Non-None value "
"should not be stored in the database."
),
)
version: int = Field(..., description=("Version of the notification model"))
async def fetch_notification(notification_id: str):
ddb = UserDynamoHandler()
notification = await sync_to_async(ddb.notifications_table.get_item)(
Key={"predictable_id": notification_id}
)
if notification.get("Item"):
return ConsoleMeUserNotification.parse_obj(notification["Item"]) | null |
162,081 | import json as original_json
import sys
import time
from collections import defaultdict
from typing import Dict
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.cache import (
retrieve_json_data_from_redis_or_s3,
store_json_results_in_redis_and_s3,
)
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.json_encoder import SetEncoder
from consoleme.lib.notifications.models import (
ConsoleMeUserNotification,
GetNotificationsForUserResponse,
)
from consoleme.lib.singleton import Singleton
async def cache_notifications_to_redis_s3() -> Dict[str, int]:
function = f"{__name__}.{sys._getframe().f_code.co_name}"
current_time = int(time.time())
log_data = {"function": function}
ddb = UserDynamoHandler()
notifications_by_user_group = defaultdict(list)
all_notifications_l = await ddb.parallel_scan_table_async(ddb.notifications_table)
changed_notifications = []
for existing_notification in all_notifications_l:
notification = ConsoleMeUserNotification.parse_obj(existing_notification)
if current_time > notification.expiration:
notification.expired = True
changed_notifications.append(notification.dict())
for user_or_group in notification.users_or_groups:
notifications_by_user_group[user_or_group].append(notification.dict())
if changed_notifications:
ddb.parallel_write_table(ddb.notifications_table, changed_notifications)
if notifications_by_user_group:
for k, v in notifications_by_user_group.items():
notifications_by_user_group[k] = original_json.dumps(v, cls=SetEncoder)
await store_json_results_in_redis_and_s3(
notifications_by_user_group,
redis_key=config.get("notifications.redis_key", "ALL_NOTIFICATIONS"),
redis_data_type="hash",
s3_bucket=config.get("notifications.s3.bucket"),
s3_key=config.get(
"notifications.s3.key", "notifications/all_notifications_v1.json.gz"
),
)
log_data["num_user_groups_for_notifications"] = len(
notifications_by_user_group.keys()
)
log_data["num_notifications"] = len(all_notifications_l)
log.debug(log_data)
return {
"num_user_groups_to_notify": len(notifications_by_user_group.keys()),
"num_notifications": len(all_notifications_l),
}
class UserDynamoHandler(BaseDynamoHandler):
def __init__(self, user_email: Optional[str] = None) -> None:
try:
self.requests_table = self._get_dynamo_table(
config.get("aws.requests_dynamo_table", "consoleme_requests_global")
)
self.users_table = self._get_dynamo_table(
config.get("aws.users_dynamo_table", "consoleme_users_global")
)
self.group_log = self._get_dynamo_table(
config.get("aws.group_log_dynamo_table", "consoleme_audit_global")
)
self.dynamic_config = self._get_dynamo_table(
config.get("aws.group_log_dynamo_table", "consoleme_config_global")
)
self.policy_requests_table = self._get_dynamo_table(
config.get(
"aws.policy_requests_dynamo_table", "consoleme_policy_requests"
)
)
self.api_health_roles_table = self._get_dynamo_table(
config.get(
"aws.api_health_apps_table_dynamo_table",
"consoleme_api_health_apps",
)
)
self.resource_cache_table = self._get_dynamo_table(
config.get(
"aws.resource_cache_dynamo_table", "consoleme_resource_cache"
)
)
self.cloudtrail_table = self._get_dynamo_table(
config.get("aws.cloudtrail_table", "consoleme_cloudtrail")
)
self.notifications_table = self._get_dynamo_table(
config.get("aws.notifications_table", "consoleme_notifications")
)
if user_email:
self.user = self.get_or_create_user(user_email)
self.affected_user = self.user
except Exception:
if config.get("development"):
log.error(
"Unable to connect to Dynamo. Trying to set user via development configuration",
exc_info=True,
)
self.user = self.sign_request(
{
"last_updated": int(time.time()),
"username": user_email,
"requests": [],
}
)
self.affected_user = self.user
else:
log.error("Unable to get Dynamo table.", exc_info=True)
raise
def write_resource_cache_data(self, data):
self.parallel_write_table(
self.resource_cache_table, data, ["resourceId", "resourceType"]
)
async def get_dynamic_config_yaml(self) -> bytes:
"""Retrieve dynamic configuration yaml."""
return await sync_to_async(self.get_dynamic_config_yaml_sync)()
def get_dynamic_config_yaml_sync(self) -> bytes:
"""Retrieve dynamic configuration yaml synchronously"""
c = b""
try:
current_config = self.dynamic_config.get_item(Key={"id": "master"})
if not current_config:
return c
compressed_config = current_config.get("Item", {}).get("config", "")
if not compressed_config:
return c
c = zlib.decompress(compressed_config.value)
except Exception: # noqa
sentry_sdk.capture_exception()
return c
def get_dynamic_config_dict(self) -> dict:
"""Retrieve dynamic configuration dictionary that can be merged with primary configuration dictionary."""
try:
loop = asyncio.get_running_loop()
except RuntimeError: # if cleanup: 'RuntimeError: There is no current event loop..'
loop = None
if loop and loop.is_running():
current_config_yaml = self.get_dynamic_config_yaml_sync()
else:
current_config_yaml = asyncio.run(self.get_dynamic_config_yaml())
config_d = yaml.safe_load(current_config_yaml)
return config_d
async def get_all_api_health_alerts(self) -> list:
"""Return all requests. If a status is specified, only requests with the specified status will be returned.
:param status:
:return:
"""
response: dict = self.api_health_roles_table.scan()
items = response.get("Items", [])
while "LastEvaluatedKey" in response:
response = self.api_health_roles_table.scan(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def get_api_health_alert_app(self, app_name) -> dict:
resp: dict = await sync_to_async(self.api_health_roles_table.get_item)(
Key={"appName": app_name}
)
return resp.get("Item", None)
async def write_api_health_alert_info(self, request, user_email: str):
"""
Writes a health alert role to the appropriate DynamoDB table
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
# enrich request
request["app_create_time"]: int = int(time.time())
request["updated_by"]: str = user_email
request["last_updated"]: int = int(time.time())
try:
await sync_to_async(self.api_health_roles_table.put_item)(
Item=self._data_to_dynamo_replace(request)
)
except Exception:
error = {
"message": "Unable to add new api_health info request",
"request": request,
"function": function,
}
log.error(error, exc_info=True)
raise
return request
async def update_api_health_alert_info(
self, request: dict, user_email=None, update_by=None, last_updated=None
):
"""
Update api_health_alert_info by roleName
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
# enrich request
if update_by:
request["updated_by"] = update_by
else:
request["updated_by"] = user_email
if last_updated:
request["last_updated"] = last_updated
else:
request["last_updated"] = int(time.time())
try:
await sync_to_async(self.api_health_roles_table.put_item)(
Item=self._data_to_dynamo_replace(request)
)
except Exception as e:
error: dict = {
"function": function,
"message": "Unable to update api_health_info request",
"request": request,
"error": str(e),
}
log.error(error, exc_info=True)
raise Exception(error)
return request
async def delete_api_health_alert_info(self, app: str) -> None:
"""
Delete api_health_alert_info by roleName
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
try:
await sync_to_async(self.api_health_roles_table.delete_item)(
Key={"appName": app}
)
except Exception:
error: dict = {
"function": function,
"message": "Unable to delete api_health info",
"app": app,
}
log.error(error, exc_info=True)
raise
async def write_policy_request(
self,
user_email: str,
justification: str,
arn: str,
policy_name: str,
policy_changes: dict,
resources: List[str],
resource_policies: List[Dict],
request_time: int = None,
request_uuid=None,
policy_status="pending",
cross_account_request: bool = False,
dry_run: bool = False,
):
"""
Writes a policy request to the appropriate DynamoDB table
dry_run will create the request format, but won't actually write it
Sample run:
write_policy_request(policy_changes)
"""
request_time = request_time or int(time.time())
# Craft the new request json
timestamp = int(time.time())
request_id = request_uuid or str(uuid.uuid4())
new_request = {
"request_id": request_id,
"arn": arn,
"status": policy_status,
"justification": justification,
"request_time": request_time,
"updated_by": user_email,
"last_updated": timestamp,
"username": user_email,
"policy_name": policy_name,
"policy_changes": json.dumps(policy_changes),
"resources": resources,
"resource_policies": resource_policies,
"cross_account_request": cross_account_request,
}
if not dry_run:
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(new_request)
)
except Exception as e:
error = f"Unable to add new policy request: {new_request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
else:
log_data = {
"function": f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}",
"request": new_request,
"message": "Dry run, skipping adding request to dynamo",
}
log.debug(log_data)
return new_request
async def write_policy_request_v2(self, extended_request: ExtendedRequestModel):
"""
Writes a policy request v2 to the appropriate DynamoDB table
Sample run:
write_policy_request_v2(request)
"""
new_request = {
"request_id": extended_request.id,
"principal": extended_request.principal.dict(),
"status": extended_request.request_status.value,
"justification": extended_request.justification,
"request_time": extended_request.timestamp,
"last_updated": int(time.time()),
"version": "2",
"extended_request": json.loads(extended_request.json()),
"username": extended_request.requester_email,
}
if extended_request.principal.principal_type == "AwsResource":
new_request["arn"] = extended_request.principal.principal_arn
elif extended_request.principal.principal_type == "HoneybeeAwsResourceTemplate":
repository_name = extended_request.principal.repository_name
resource_identifier = extended_request.principal.resource_identifier
new_request["arn"] = f"{repository_name}-{resource_identifier}"
else:
raise Exception("Invalid principal type")
log_data = {
"function": f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}",
"message": "Writing policy request v2 to Dynamo",
"request": new_request,
}
log.debug(log_data)
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(new_request)
)
log_data[
"message"
] = "Successfully finished writing policy request v2 to Dynamo"
log.debug(log_data)
except Exception as e:
log_data["message"] = "Error occurred writing policy request v2 to Dynamo"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
error = f"{log_data['message']}: {str(e)}"
raise Exception(error)
return new_request
async def update_policy_request(self, updated_request):
"""
Update a policy request by request ID
Sample run:
update_policy_request(policy_changes)
"""
updated_request["last_updated"] = int(time.time())
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(updated_request)
)
except Exception as e:
error = f"Unable to add updated policy request: {updated_request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return updated_request
async def get_policy_requests(self, arn=None, request_id=None):
"""Reads a policy request from the appropriate DynamoDB table"""
if not arn and not request_id:
raise Exception("Must pass in ARN or policy request ID")
if request_id:
requests = self.policy_requests_table.query(
KeyConditionExpression="request_id = :ri",
ExpressionAttributeValues={":ri": request_id},
)
else:
requests = self.policy_requests_table.query(
KeyConditionExpression="arn = :arn",
ExpressionAttributeValues={":arn": arn},
)
matching_requests = []
if requests["Items"]:
items = self._data_from_dynamo_replace(requests["Items"])
items = await self.convert_policy_requests_to_v3(items)
matching_requests.extend(items)
return matching_requests
async def convert_policy_requests_to_v3(self, requests):
# Remove this function and calls to this function after a grace period of
changed = False
for request in requests:
if not request.get("version") in ["2"]:
continue
if request.get("extended_request") and not request.get("principal"):
principal_arn = request.pop("arn")
request["principal"] = {
"principal_arn": principal_arn,
"principal_type": "AwsResource",
}
request["extended_request"]["principal"] = {
"principal_arn": principal_arn,
"principal_type": "AwsResource",
}
request.pop("arn", None)
changes = (
request.get("extended_request", {})
.get("changes", {})
.get("changes", [])
)
for change in changes:
if not change.get("principal_arn"):
continue
if not change.get("version") in ["2.0", "2", 2]:
continue
change["principal"] = {
"principal_arn": change["principal_arn"],
"principal_type": "AwsResource",
}
change.pop("principal_arn")
change["version"] = "3.0"
changed = True
if changed:
self.parallel_write_table(self.policy_requests_table, requests)
return requests
async def get_all_policy_requests(
self, status: Optional[str] = "pending"
) -> List[Dict[str, Union[int, List[str], str]]]:
"""Return all policy requests. If a status is specified, only requests with the specified status will be
returned.
:param status:
:return:
"""
requests = await sync_to_async(self.parallel_scan_table)(
self.policy_requests_table
)
requests = await self.convert_policy_requests_to_v3(requests)
return_value = []
if status:
for item in requests:
if status and item["status"] == status:
return_value.append(item)
else:
return_value = requests
return return_value
async def update_dynamic_config(self, config: str, updated_by: str) -> None:
"""Take a YAML config and writes to DDB (The reason we use YAML instead of JSON is to preserve comments)."""
# Validate that config loads as yaml, raises exception if not
yaml.safe_load(config)
stats.count("update_dynamic_config", tags={"updated_by": updated_by})
current_config_entry = self.dynamic_config.get_item(Key={"id": "master"})
if current_config_entry.get("Item"):
old_config = {
"id": current_config_entry["Item"]["updated_at"],
"updated_by": current_config_entry["Item"]["updated_by"],
"config": current_config_entry["Item"]["config"],
"updated_at": str(int(time.time())),
}
self.dynamic_config.put_item(Item=self._data_to_dynamo_replace(old_config))
new_config = {
"id": "master",
"config": zlib.compress(config.encode()),
"updated_by": updated_by,
"updated_at": str(int(time.time())),
}
self.dynamic_config.put_item(Item=self._data_to_dynamo_replace(new_config))
def validate_signature(self, items):
signature = items.pop("signature")
if isinstance(signature, Binary):
signature = signature.value
json_request = json.dumps(items, sort_keys=True)
if not crypto.verify(json_request, signature):
raise Exception(f"Invalid signature for request: {json_request}")
def sign_request(
self, user_entry: Dict[str, Union[Decimal, List[str], Binary, str]]
) -> Dict[str, Union[Decimal, List[str], str, bytes]]:
"""
Sign the request and returned request with signature
:param user_entry:
:return:
"""
# Remove old signature if it exists
user_entry.pop("signature", None)
user_entry = self._data_from_dynamo_replace(user_entry)
json_request = json.dumps(user_entry, sort_keys=True, use_decimal=True)
sig = crypto.sign(json_request)
user_entry["signature"] = sig
return user_entry
async def authenticate_user(self, login_attempt) -> AuthenticationResponse:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {
"function": function,
"user_email": login_attempt.username,
"after_redirect_uri": login_attempt.after_redirect_uri,
}
user_entry = await sync_to_async(self.users_table.query)(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": login_attempt.username},
)
user = None
generic_error = ["User doesn't exist, or password is incorrect. "]
if user_entry and "Items" in user_entry and len(user_entry["Items"]) == 1:
user = user_entry["Items"][0]
if not user:
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = f"Unable to find user: {login_attempt.username}"
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
if not user.get("password"):
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = "User exists, but doesn't have a password stored in the database"
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
password_hash_matches = bcrypt.checkpw(
login_attempt.password.encode("utf-8"), user["password"].value
)
if not password_hash_matches:
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = "Password does not match. "
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
return AuthenticationResponse(
authenticated=True, username=user["username"], groups=user["groups"]
)
def create_user(
self,
user_email,
password: Optional[str] = None,
groups: Optional[List[str]] = None,
):
if not groups:
groups = []
timestamp = int(time.time())
unsigned_user_entry = {
"created": timestamp,
"last_updated": timestamp,
"username": user_email,
"requests": [],
"groups": groups,
}
if password:
pw = bytes(password, "utf-8")
salt = bcrypt.gensalt()
unsigned_user_entry["password"] = bcrypt.hashpw(pw, salt)
user_entry = self.sign_request(unsigned_user_entry)
try:
self.users_table.put_item(Item=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to add user submission: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return user_entry
def update_user(
self,
user_email,
password: Optional[str] = None,
groups: Optional[List[str]] = None,
):
if not groups:
groups = []
user_ddb = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
user = None
if user_ddb and "Items" in user_ddb and len(user_ddb["Items"]) == 1:
user = user_ddb["Items"][0]
if not user:
raise DataNotRetrievable(f"Unable to find user: {user_email}")
timestamp = int(time.time())
if password:
pw = bytes(password, "utf-8")
salt = bcrypt.gensalt()
user["password"] = bcrypt.hashpw(pw, salt)
if groups:
user["groups"] = groups
user["last_updated"] = timestamp
user_entry = self.sign_request(user)
try:
self.users_table.put_item(Item=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to add user submission: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return user_entry
def delete_user(self, user_email):
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user_entry = {"username": user_email}
try:
self.users_table.delete_item(Key=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to delete user: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
async def get_user(
self, user_email: str
) -> Optional[Dict[str, Union[Decimal, List[str], Binary, str]]]:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
if user and "Items" in user and len(user["Items"]) == 1:
return user["Items"][0]
return None
def get_or_create_user(
self, user_email: str
) -> Dict[str, Union[Decimal, List[str], Binary, str]]:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
items = []
if user and "Items" in user:
items = user["Items"]
if not items:
return self.create_user(user_email)
return items[0]
def resolve_request_ids(
self, request_ids: List[str]
) -> List[Dict[str, Union[int, str]]]:
requests = []
for request_id in request_ids:
request = self.requests_table.query(
KeyConditionExpression="request_id = :ri",
ExpressionAttributeValues={":ri": request_id},
)
if request["Items"]:
items = self._data_from_dynamo_replace(request["Items"])
requests.append(items[0])
else:
raise NoMatchingRequest(
f"No matching request for request_id: {request_id}"
)
return requests
def add_request_id_to_user(
self,
affected_user: Dict[str, Union[Decimal, List[str], Binary, str]],
request_id: str,
) -> None:
affected_user["requests"].append(request_id)
self.users_table.put_item(
Item=self._data_to_dynamo_replace(self.sign_request(affected_user))
)
def add_request(
self,
user_email: str,
group: str,
justification: str,
request_time: None = None,
status: str = "pending",
updated_by: Optional[str] = None,
) -> Dict[str, Union[int, str]]:
"""
Add a user request to the dynamo table
Sample run:
add_request("user@example.com", "engtest", "because")
:param user_email: Email address of user
:param group: Name of group user is requesting access to
:param justification:
:param request_id:
:param request_time:
:param status:
:param updated_by:
:return:
"""
"""
Request:
group
justification
role
request_time
approval_time
updated_by
approval_reason
status
user@example.com:
requests: []
last_updated: 1
signature: xxxx
#pending: []
#expired: []
# How to expire requests if soemeone maliciously deletes content
# How to query for all approved requests for group X
# What if we want to send email saying your request is expiring in 7 days? Maybe celery to query all
# What about concept of request ID? Maybe base64 encoded thing?
# Need an all-in-one page to show all pending requests, all expired/approved requests
"""
request_time = request_time or int(time.time())
stats.count("new_group_request", tags={"user": user_email, "group": group})
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
# Get current user. Create if they do not already exist
# self.user = self.get_or_create_user(user_email)
# Get current user requests, which will validate existing signature
# existing_request_ids = self.user["requests"]
# existing_requests = self.resolve_request_ids(existing_request_ids)
existing_pending_requests_for_group = self.get_requests_by_user(
user_email, group, status="pending"
)
# Craft the new request json
timestamp = int(time.time())
request_id = str(uuid.uuid4())
new_request = {
"request_id": request_id,
"group": group,
"status": status,
"justification": justification,
"request_time": request_time,
"updated_by": updated_by,
"last_updated": timestamp,
"username": user_email,
}
# See if user already has an active or pending request for the group
if existing_pending_requests_for_group:
for request in existing_pending_requests_for_group:
raise PendingRequestAlreadyExists(
f"Pending request for group: {group} already exists: {request}"
)
try:
self.requests_table.put_item(Item=self._data_to_dynamo_replace(new_request))
except Exception as e:
error = {
"error": f"Unable to add user request: {str(e)}",
"request": new_request,
}
log.error(error, exc_info=True)
raise Exception(error)
self.add_request_id_to_user(self.affected_user, request_id)
return new_request
async def get_all_requests(self, status=None):
"""Return all requests. If a status is specified, only requests with the specified status will be returned.
:param status:
:return:
"""
items = await sync_to_async(self.parallel_scan_table)(self.requests_table)
return_value = []
if status:
for item in items:
new_json = []
for j in item["json"]:
if j["status"] == status:
new_json.append(j)
item["json"] = new_json
if new_json:
return_value.append(item)
else:
return_value = items
return return_value
def get_requests_by_user(
self,
user_email: str,
group: str = None,
status: str = None,
use_cache: bool = False,
) -> dict:
"""Get requests by user. Group and status can also be specified to filter results.
:param user_email:
:param group:
:param status:
:return:
"""
red_key = f"USER_REQUESTS_{user_email}-{group}-{status}"
if use_cache:
requests_to_return = red.get(red_key)
if requests_to_return:
return json.loads(requests_to_return)
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
existing_request_ids = self.affected_user["requests"]
existing_requests = self.resolve_request_ids(existing_request_ids)
requests_to_return = []
if existing_requests:
for request in existing_requests:
if group and request["group"] != group:
continue
if status and request["status"] != status:
continue
requests_to_return.append(request)
if use_cache:
red.setex(red_key, 120, json.dumps(requests_to_return))
return requests_to_return
def change_request_status(
self, user_email, group, new_status, updated_by=None, reviewer_comments=None
):
"""
:param user:
:param status:
:param request_id:
:return:
"""
stats.count(
"update_group_request",
tags={
"user": user_email,
"group": group,
"new_status": new_status,
"updated_by": updated_by,
},
)
modified_request = None
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
timestamp = int(time.time())
if new_status not in POSSIBLE_STATUSES:
raise Exception(
f"Invalid status. Status must be one of {POSSIBLE_STATUSES}"
)
if new_status == "approved" and not updated_by:
raise Exception(
"You must provide `updated_by` to change a request status to approved."
)
existing_requests = self.get_requests_by_user(user_email)
if existing_requests:
updated = False
for request in existing_requests:
if request["group"] == group:
request["updated_by"] = updated_by
request["status"] = new_status
request["last_updated"] = timestamp
request["reviewer_comments"] = reviewer_comments
modified_request = request
try:
self.requests_table.put_item(
Item=self._data_to_dynamo_replace(request)
)
except Exception as e:
error = f"Unable to add user request: {request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
updated = True
if not updated:
raise NoExistingRequest(
f"Unable to find existing request for user: {user_email} and group: {group}."
)
else:
raise NoExistingRequest(
f"Unable to find existing requests for user: {user_email}"
)
return modified_request
def change_request_status_by_id(
self,
request_id: str,
new_status: str,
updated_by: Optional[str] = None,
reviewer_comments: Optional[str] = None,
) -> Dict[str, Union[int, str]]:
"""
Change request status by ID
:param request_id:
:param new_status:
:param updated_by:
:return: new requests
"""
modified_request = None
if new_status == "approved" and not updated_by:
raise Exception(
"You must provide `updated_by` to change a request status to approved."
)
requests = self.resolve_request_ids([request_id])
if new_status not in POSSIBLE_STATUSES:
raise Exception(
f"Invalid status. Status must be one of {POSSIBLE_STATUSES}"
)
for request in requests:
request["status"] = new_status
request["updated_by"] = updated_by
request["last_updated"] = int(time.time())
request["reviewer_comments"] = reviewer_comments
modified_request = request
try:
self.requests_table.put_item(Item=self._data_to_dynamo_replace(request))
except Exception as e:
error = f"Unable to add user request: {request} : {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return modified_request
def get_all_policies(self):
"""Return all policies."""
response = self.policies_table.scan()
items = []
if response and "Items" in response:
items = self._data_from_dynamo_replace(response["Items"])
while "LastEvaluatedKey" in response:
response = self.policies_table.scan(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def create_group_log_entry(
self,
group: str,
username: str,
updated_by: str,
action: str,
updated_at: None = None,
extra: None = None,
) -> None:
updated_at = updated_at or int(time.time())
log_id = str(uuid.uuid4())
log_entry = {
"uuid": log_id,
"group": group,
"username": username,
"updated_by": updated_by,
"updated_at": updated_at,
"action": action,
"extra": extra,
}
self.group_log.put_item(Item=self._data_to_dynamo_replace(log_entry))
async def get_all_audit_logs(self) -> List[Dict[str, Union[int, None, str]]]:
response = await sync_to_async(self.group_log.scan)()
items = []
if response and "Items" in response:
items = self._data_from_dynamo_replace(response["Items"])
while "LastEvaluatedKey" in response:
response = await sync_to_async(self.group_log.scan)(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def get_all_pending_requests(self):
return await self.get_all_requests(status="pending")
def batch_write_cloudtrail_events(self, items):
with self.cloudtrail_table.batch_writer(
overwrite_by_pkeys=["arn", "request_id"]
) as batch:
for item in items:
batch.put_item(Item=self._data_to_dynamo_replace(item))
return True
async def get_top_cloudtrail_errors_by_arn(self, arn, n=5):
response: dict = await sync_to_async(self.cloudtrail_table.query)(
KeyConditionExpression=Key("arn").eq(arn)
)
items = response.get("Items", [])
aggregated_errors = defaultdict(dict)
for item in items:
if int(item["ttl"]) < int(time.time()):
continue
event_call = item["event_call"]
event_resource = item.get("resource", "")
event_string = f"{event_call}|||{event_resource}"
if not aggregated_errors.get(event_string):
aggregated_errors[event_string]["count"] = 0
aggregated_errors[event_string]["generated_policy"] = item.get(
"generated_policy", {}
)
aggregated_errors[event_string]["count"] += 1
top_n_errors = {
k: v
for k, v in sorted(
aggregated_errors.items(),
key=lambda item: item[1]["count"],
reverse=True,
)[:n]
}
return top_n_errors
def count_arn_errors(self, error_count, items):
for item in items:
arn = item.get("arn")
if not error_count.get(arn):
error_count[arn] = 0
error_count[arn] += item.get("count", 1)
return error_count
class ConsoleMeUserNotification(BaseModel):
predictable_id: str = Field(
...,
description=(
"Predictable ID for this notification. Generally used to prevent duplicate notifications"
),
)
type: str = Field(
...,
description=(
"Each class of notification should be given a separate type, "
"IE: `cloudtrail_generated_policy` or `proxy_generated_policy"
),
)
users_or_groups: Set[str] = Field(
..., description="Users or groups who should see the notification"
)
event_time: int = Field(..., description="Time that the event took place")
expiration: int = Field(
..., description="Time that this entry should stop notifying people"
)
expired: bool = Field(
...,
description="A more obvious indicator about whether a notification has expired",
)
header: Optional[str] = Field(
None, description="Bolded text (Header) for the notification"
)
message: str = Field(
...,
description="An (optionally markdown) formatted message to show to users in the UI",
)
message_actions: List[ConsoleMeUserNotificationAction] = Field(
...,
description=(
"An optional list of actions to make available to the user. These will be shown below the notification."
),
)
details: Dict[str, Any] = Field(
...,
description=(
"Extra details about the notification for power users. "
"This will be accessible to the user in the UI, but not visible by default"
),
)
read_by_users: List[str] = Field(
...,
description=(
"List of users the notification is `read` for. It will show up in the user's list of notifications, "
"but will not be shown as `unread` nor be included in the unread counter."
),
)
read_by_all: bool = Field(
False,
description=(
"Notification is `marked as read` for all users and will not appear as an unread notification for "
"any users."
),
)
hidden_for_users: List[str] = Field(
...,
description=(
"List of users the notification is `hidden` for. It will not appear at all in the user's list of "
"notifications."
),
)
hidden_for_all: bool = Field(
False,
description=(
"Notification is `marked as hidden` for all users, and will not appear in the notificaiton list for "
"any user."
),
)
read_for_current_user: bool = Field(
None,
description=(
"Convenience variable to mark a notification as read for current user when retrieving notification. "
"This makes it so the frontend doesn't need to do any computation to figure it out. A Non-None value "
"should not be stored in the database."
),
)
version: int = Field(..., description=("Version of the notification model"))
async def write_notification(notification: ConsoleMeUserNotification):
ddb = UserDynamoHandler()
await sync_to_async(ddb.notifications_table.put_item)(
Item=ddb._data_to_dynamo_replace(notification.dict())
)
await cache_notifications_to_redis_s3()
return True | null |
162,082 | from typing import Dict, List
from consoleme.config import config
The provided code snippet includes necessary dependencies for implementing the `get_custom_page_header` function. Write a Python function `async def get_custom_page_header(user: str, user_groups: List[str]) -> Dict[str, str]` to solve the following problem:
Args: user: The user's e-mail address user_groups: the user's group memberships Returns: Headers to show on the page. These headers can be specific to the user's group memberships, or the user's email address, or generic. If a configuration is not set, a header will not be shown. Example: Visit https://YOUR_CONSOLEME_DOMAIN/config Add this to the page: ``` custom_headers_for_group_members: - users_or_groups: - you@example.com - a_group@example.com title: Important message! message: Read this! ```
Here is the function:
async def get_custom_page_header(user: str, user_groups: List[str]) -> Dict[str, str]:
"""
Args:
user: The user's e-mail address
user_groups: the user's group memberships
Returns:
Headers to show on the page. These headers can be specific to the user's group memberships, or the user's
email address, or generic. If a configuration is not set, a header will not be shown.
Example:
Visit https://YOUR_CONSOLEME_DOMAIN/config
Add this to the page:
```
custom_headers_for_group_members:
- users_or_groups:
- you@example.com
- a_group@example.com
title: Important message!
message: Read this!
```
"""
if config.get("example_config.is_example_config", False):
return {
"custom_header_message_title": config.get("example_config.title"),
"custom_header_message_text": config.get("example_config.text"),
"custom_header_message_route": config.get("example_config.routes"),
}
custom_headers_for_group_members = config.get(
"dynamic_config.custom_headers_for_group_members", []
)
for custom_header in custom_headers_for_group_members:
for header_group in custom_header.get("users_or_groups", []):
if header_group in user_groups or user == header_group:
return {
"custom_header_message_title": custom_header.get("title", ""),
"custom_header_message_text": custom_header.get("message", ""),
"custom_header_message_route": custom_header.get("route", ".*"),
}
return {
"custom_header_message_title": config.get(
"headers.custom_header_message.title", ""
),
"custom_header_message_text": config.get(
"headers.custom_header_message.text", ""
),
"custom_header_message_route": config.get(
"headers.custom_header_message.route", ".*"
),
} | Args: user: The user's e-mail address user_groups: the user's group memberships Returns: Headers to show on the page. These headers can be specific to the user's group memberships, or the user's email address, or generic. If a configuration is not set, a header will not be shown. Example: Visit https://YOUR_CONSOLEME_DOMAIN/config Add this to the page: ``` custom_headers_for_group_members: - users_or_groups: - you@example.com - a_group@example.com title: Important message! message: Read this! ``` |
162,083 | import asyncio
import re
import sys
import time
import uuid
from hashlib import sha256
from typing import Dict, List, Optional, Union
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from botocore.exceptions import ClientError
from cloudaux.aws.iam import get_managed_policy_document
from cloudaux.aws.sts import boto3_cached_conn
from policy_sentry.util.actions import get_service_from_action
from policy_sentry.util.arns import parse_arn
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
NoMatchingRequest,
ResourceNotFound,
Unauthorized,
UnsupportedChangeType,
)
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
create_or_update_managed_policy,
fetch_resource_details,
generate_updated_resource_policy,
get_bucket_location_with_fallback,
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_resource_policy,
get_service_from_arn,
sanitize_session_name,
)
from consoleme.lib.change_request import generate_policy_name
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.policies import (
can_move_back_to_pending_v2,
can_update_cancel_requests_v2,
get_url_for_resource,
invalid_characters_in_policy,
send_communications_new_comment,
send_communications_policy_change_request_v2,
)
from consoleme.lib.templated_resources.requests import (
generate_honeybee_request_from_change_model_array,
)
from consoleme.lib.v2.aws_principals import get_role_details, get_user_details
from consoleme.models import (
Action,
ActionResult,
ApplyChangeModificationModel,
AssumeRolePolicyChangeModel,
CancelChangeModificationModel,
ChangeModel,
ChangeModelArray,
Command,
CommentModel,
CommentRequestModificationModel,
ExtendedAwsPrincipalModel,
ExtendedRequestModel,
GenericFileChangeModel,
InlinePolicyChangeModel,
ManagedPolicyChangeModel,
ManagedPolicyResourceChangeModel,
PermissionsBoundaryChangeModel,
PolicyModel,
PolicyRequestModificationRequestModel,
PolicyRequestModificationResponseModel,
RequestCreationModel,
RequestCreationResponse,
RequestStatus,
ResourceModel,
ResourcePolicyChangeModel,
ResourceTagChangeModel,
Status,
TagAction,
UpdateChangeModificationModel,
UserModel,
)
log = config.get_logger()
auth = get_plugin_by_name(config.get("plugins.auth", "default_auth"))()
async def generate_resource_policies(extended_request: ExtendedRequestModel, user: str):
"""
Generates the resource policies and adds it to the extended request.
Note: generating resource policy is only supported for when the principal ARN is a role right now.
:param extended_request: ExtendedRequestModel
:param user: username
:return:
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": extended_request.principal,
"request": extended_request.dict(),
"message": "Generating resource policies",
}
log.debug(log_data)
supported_resource_policies = config.get(
"policies.supported_resource_types_for_policy_application", ["s3", "sqs", "sns"]
)
supported_trust_policy_permissions = config.get(
"policies.supported_trust_policy_permissions",
[
"sts:AssumeRole",
"sts:TagSession",
"sts:AssumeRoleWithSAML",
"sts:AssumeRoleWithWebIdentity",
],
)
if extended_request.principal.principal_type == "AwsResource":
principal_arn = extended_request.principal.principal_arn
role_account_id = await get_resource_account(principal_arn)
arn_parsed = parse_arn(principal_arn)
if arn_parsed["service"] != "iam" or arn_parsed["resource"] != "role":
log_data[
"message"
] = "ARN type not supported for generating resource policy changes."
log.debug(log_data)
return extended_request
resource_policy = {"Version": "2012-10-17", "Statement": []}
resource_policy_sha = sha256(
json.dumps(resource_policy, escape_forward_slashes=False).encode()
).hexdigest()
if not arn_parsed.get("resource_path") or not arn_parsed.get("service"):
return extended_request
primary_principal_resource_model = ResourceModel(
arn=principal_arn,
name=arn_parsed["resource_path"].split("/")[-1],
account_id=role_account_id,
resource_type=arn_parsed["service"],
)
auto_generated_resource_policy_changes = []
# Create resource policy stubs for current resources that are used
for policy_change in extended_request.changes.changes:
if policy_change.change_type == "inline_policy":
policy_change.resources = await get_resources_from_policy_change(
policy_change
)
for resource in policy_change.resources:
resource_account_id = await get_resource_account(resource.arn)
if (
resource_account_id != role_account_id
and resource.resource_type != "iam"
and resource.resource_type in supported_resource_policies
):
# Cross account
auto_generated_resource_policy_changes.append(
ResourcePolicyChangeModel(
arn=resource.arn,
policy=PolicyModel(
policy_document=resource_policy,
policy_sha256=resource_policy_sha,
),
change_type="resource_policy",
principal=extended_request.principal,
status=Status.not_applied,
source_change_id=policy_change.id,
id=str(uuid.uuid4()),
resources=[primary_principal_resource_model],
autogenerated=True,
)
)
elif (
resource_account_id != role_account_id
and resource.resource_type == "iam"
):
resource_added = False
for statement in policy_change.policy.policy_document.get(
"Statement", []
):
if resource.arn in statement.get("Resource"):
# check if action includes supported trust policy permissions
statement_actions = statement.get("Action", [])
statement_actions = (
statement_actions
if isinstance(statement_actions, list)
else [statement_actions]
)
for action in statement_actions:
if action in supported_trust_policy_permissions:
# Cross account sts policy
auto_generated_resource_policy_changes.append(
ResourcePolicyChangeModel(
arn=resource.arn,
policy=PolicyModel(
policy_document=resource_policy,
policy_sha256=resource_policy_sha,
),
change_type="sts_resource_policy",
principal=extended_request.principal,
status=Status.not_applied,
source_change_id=policy_change.id,
id=str(uuid.uuid4()),
resources=[
primary_principal_resource_model
],
autogenerated=True,
)
)
resource_added = True
break
if resource_added:
break
extended_request.changes.changes.extend(auto_generated_resource_policy_changes)
if len(auto_generated_resource_policy_changes) > 0:
extended_request.cross_account = True
log_data["message"] = "Finished generating resource policies"
log_data["request"] = extended_request.dict()
log.debug(log_data)
return extended_request
async def validate_inline_policy_change(
change: InlinePolicyChangeModel, user: str, role: ExtendedAwsPrincipalModel
):
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": change.principal.dict(),
"policy_name": change.policy_name,
"request": change.dict(),
"message": "Validating inline policy change",
}
log.debug(log_data)
if (
await invalid_characters_in_policy(change.policy.policy_document)
or await invalid_characters_in_policy(change.policy_name)
or await invalid_characters_in_policy(change.policy.version)
):
log_data["message"] = "Invalid characters were detected in the policy."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
# Can't detach a new policy
if change.new and change.action == Action.detach:
log_data["message"] = "Can't detach an inline policy that is new."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
seen_policy_name = False
for existing_policy in role.inline_policies:
# Check if a new policy is being created, ensure that we don't overwrite another policy with same name
if change.new and change.policy_name == existing_policy.get("PolicyName"):
log_data[
"message"
] = f"Inline Policy with the name {change.policy_name} already exists."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
# Check if policy being updated is the same as existing policy.
if (
not change.new
and change.policy.policy_document == existing_policy.get("PolicyDocument")
and change.policy_name == existing_policy.get("PolicyName")
and change.action == Action.attach
):
log_data[
"message"
] = f"No changes were found between the updated and existing policy for policy {change.policy_name}."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if change.policy_name == existing_policy.get("PolicyName"):
seen_policy_name = True
# Trying to detach inline policy with name that isn't attached
if change.action == Action.detach and not seen_policy_name:
log_data[
"message"
] = f"An inline policy named '{seen_policy_name}' is not attached, so we cannot remove it"
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if change.action == Action.attach and not seen_policy_name and not change.new:
log_data[
"message"
] = f"Inline policy {change.policy_name} not seen but request claims change is not new"
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
# TODO: check sha in the request (future feature)
# If here, then that means inline policy is validated
async def validate_permissions_boundary_change(
change: PermissionsBoundaryChangeModel, user: str, role: ExtendedAwsPrincipalModel
):
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": change.principal.dict(),
"request": change.dict(),
"message": "Validating permissions boundary change",
}
log.info(log_data)
policy_name = change.arn.split("/")[-1]
if await invalid_characters_in_policy(policy_name):
log_data["message"] = "Invalid characters were detected in the policy name."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if change.action == Action.attach:
if not role.permissions_boundary:
return
log_data["message"] = (
"A permissions boundary is already attached to this role. "
"Only one permission boundary can be attached to a role."
)
log.error(log_data)
raise InvalidRequestParameter(
"A permissions boundary is already attached to this role. "
"Only one permission boundary can be attached to a role."
)
elif change.action == Action.detach:
# check to make sure permissions boundary is actually attached to the role
if change.arn == role.permissions_boundary.get("PermissionsBoundaryArn"):
return
log_data[
"message"
] = "The Permissions Boundary you are trying to detach is not attached to this role."
log.error(log_data)
raise InvalidRequestParameter(
f"{change.arn} is not attached to this role as a permissions boundary"
)
async def validate_managed_policy_change(
change: ManagedPolicyChangeModel, user: str, role: ExtendedAwsPrincipalModel
):
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": change.principal.dict(),
"request": change.dict(),
"message": "Validating managed policy change",
}
log.info(log_data)
policy_name = change.arn.split("/")[-1]
if await invalid_characters_in_policy(policy_name):
log_data["message"] = "Invalid characters were detected in the policy name."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if change.action == Action.attach:
# check to make sure managed policy is not already attached
for existing_policy in role.managed_policies:
if change.arn == existing_policy.get("PolicyArn"):
log_data[
"message"
] = "Managed Policy with that ARN already attached to this role."
log.error(log_data)
raise InvalidRequestParameter(
f"{change.arn} already attached to this role"
)
elif change.action == Action.detach:
# check to make sure managed policy is actually attached to role
seen = False
for existing_policy in role.managed_policies:
if change.arn == existing_policy.get("PolicyArn"):
seen = True
break
if not seen:
log_data[
"message"
] = "The Managed Policy you are trying to detach is not attached to this role."
log.error(log_data)
raise InvalidRequestParameter(f"{change.arn} is not attached to this role")
# TODO: check policy name is same what ARN claims
async def validate_managed_policy_resource_change(
change: ManagedPolicyResourceChangeModel,
policy_name: str,
user: str,
managed_policy_resource: Dict,
):
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": change.principal.dict(),
"request": change.dict(),
"message": "Validating managed policy resource change",
}
log.info(log_data)
if await invalid_characters_in_policy(
policy_name
) or await invalid_characters_in_policy(change.policy.policy_document):
log_data[
"message"
] = "Invalid characters were detected in the policy name or document."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if change.new and managed_policy_resource:
# change is claiming to be a new policy, but it already exists in AWS
log_data["message"] = "Managed policy with that ARN already exists"
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
elif not change.new and not managed_policy_resource:
# change is claiming to update policy, but it doesn't exist in AWS
log_data["message"] = "Managed policy with that ARN doesn't exist"
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if not change.new:
if change.policy.policy_document == managed_policy_resource:
log_data[
"message"
] = "No changes detected between current and proposed policy"
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
async def validate_resource_tag_change(
change: ResourceTagChangeModel, user: str, role: ExtendedAwsPrincipalModel
):
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": change.principal.dict(),
"request": change.dict(),
"role": role,
"message": "Validating resource tag change",
}
log.debug(log_data)
# TODO: Add validation here
return
async def validate_assume_role_policy_change(
change: AssumeRolePolicyChangeModel, user: str, role: ExtendedAwsPrincipalModel
):
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": change.principal.dict(),
"request": change.dict(),
"message": "Validating assume role policy change",
}
log.debug(log_data)
if await invalid_characters_in_policy(
change.policy.policy_document
) or await invalid_characters_in_policy(change.policy.version):
log_data["message"] = "Invalid characters were detected in the policy."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
# Check if policy being updated is the same as existing policy.
if change.policy.policy_document == role.assume_role_policy_document:
log_data[
"message"
] = "No changes were found between the updated and existing assume role policy."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
async def populate_old_policies(
extended_request: ExtendedRequestModel,
user: str,
principal: Optional[ExtendedAwsPrincipalModel] = None,
) -> ExtendedRequestModel:
"""
Populates the old policies for each inline policy.
Note: Currently only applicable when the principal ARN is a role and for old inline_policies, assume role policy
:param extended_request: ExtendedRequestModel
:param user: username
:return ExtendedRequestModel
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": extended_request.principal,
"request": extended_request.dict(),
"message": "Populating old policies",
}
log.debug(log_data)
if extended_request.principal.principal_type == "AwsResource":
principal_arn = extended_request.principal.principal_arn
role_account_id = await get_resource_account(principal_arn)
arn_parsed = parse_arn(principal_arn)
if arn_parsed["service"] != "iam" or arn_parsed["resource"] not in [
"role",
"user",
]:
log_data[
"message"
] = "ARN type not supported for populating old policy changes."
log.debug(log_data)
return extended_request
principal_name = arn_parsed["resource_path"].split("/")[-1]
if not principal:
if arn_parsed["resource"] == "role":
principal = await get_role_details(
role_account_id,
role_name=principal_name,
extended=True,
force_refresh=True,
)
elif arn_parsed["resource"] == "user":
principal = await get_user_details(
role_account_id,
user_name=principal_name,
extended=True,
force_refresh=True,
)
for change in extended_request.changes.changes:
if change.status == Status.applied:
# Skip changing any old policies that are saved for historical record (already applied)
continue
if change.change_type == "assume_role_policy":
change.old_policy = PolicyModel(
policy_sha256=sha256(
json.dumps(
principal.assume_role_policy_document,
escape_forward_slashes=False,
).encode()
).hexdigest(),
policy_document=principal.assume_role_policy_document,
)
elif change.change_type == "inline_policy" and not change.new:
for existing_policy in principal.inline_policies:
if change.policy_name == existing_policy.get("PolicyName"):
change.old_policy = PolicyModel(
policy_sha256=sha256(
json.dumps(
existing_policy.get("PolicyDocument"),
escape_forward_slashes=False,
).encode()
).hexdigest(),
policy_document=existing_policy.get("PolicyDocument"),
)
break
log_data["message"] = "Done populating old policies"
log_data["request"] = extended_request.dict()
log.debug(log_data)
return extended_request
async def populate_old_managed_policies(
extended_request: ExtendedRequestModel,
user: str,
) -> Dict:
"""
Populates the old policies for a managed policy resource change.
:param extended_request: ExtendedRequestModel
:param user: username
:return ExtendedRequestModel
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": extended_request.principal,
"request": extended_request.dict(),
"message": "Populating old managed policies",
}
log.debug(log_data)
managed_policy_resource = None
result = {"changed": False}
if extended_request.principal.principal_type == "AwsResource":
principal_arn = extended_request.principal.principal_arn
arn_parsed = parse_arn(principal_arn)
if arn_parsed["service"] != "iam" or arn_parsed["resource"] != "policy":
log_data[
"message"
] = "ARN type not supported for populating old managed policy changes."
log.debug(log_data)
return result
try:
managed_policy_resource = await sync_to_async(get_managed_policy_document)(
policy_arn=principal_arn,
account_number=arn_parsed["account"],
assume_role=config.get("policies.role_name"),
region=config.region,
retry_max_attempts=2,
)
except ClientError as e:
if e.response["Error"]["Code"] == "NoSuchEntity":
# Could be a new managed policy, hence not found, in this case there are no old policies
return result
raise
else:
# TODO: Add Honeybee Support for editing managed policies
return result
for change in extended_request.changes.changes:
if (
change.status == Status.applied
or change.change_type != "managed_policy_resource"
):
# Skip changing any old policies that are saved for historical record (already applied)
continue
if managed_policy_resource:
old_policy_sha256 = sha256(
json.dumps(
managed_policy_resource, escape_forward_slashes=False
).encode()
).hexdigest()
if (
change.old_policy
and old_policy_sha256 == change.old_policy.policy_sha256
):
# Old policy hasn't changed since last refresh of page, no need to generate resource policy again
continue
result["changed"] = True
change.old_policy = PolicyModel(
policy_sha256=sha256(
json.dumps(
managed_policy_resource,
escape_forward_slashes=False,
).encode()
).hexdigest(),
policy_document=managed_policy_resource,
)
log_data["message"] = "Done populating old managed policies"
log_data["request"] = extended_request.dict()
log.debug(log_data)
result["extended_request"] = extended_request
return result
class InvalidRequestParameter(BaseException):
"""Invalid Request Parameter passed to function"""
def __init__(self, msg=""):
stats.count("InvalidRequestParameter")
super().__init__(msg)
class UnsupportedChangeType(BaseException):
"""Unsupported Change Type"""
def __init__(self, msg=""):
stats.count("UnsupportedChangeType")
super().__init__(msg)
class ResourceNotFound(BaseException):
"""Resource Not Found"""
def __init__(self, msg=""):
stats.count("ResourceNotFound")
super().__init__(msg)
async def get_resource_account(arn: str) -> str:
"""Return the AWS account ID that owns a resource.
In most cases, this will pull the ID directly from the ARN.
If we are unsuccessful in pulling the account from ARN, we try to grab it from our resources cache
"""
red = await RedisHandler().redis()
resource_account: str = get_account_from_arn(arn)
if resource_account:
return resource_account
resources_from_aws_config_redis_key: str = config.get(
"aws_config_cache.redis_key", "AWSCONFIG_RESOURCE_CACHE"
)
if not red.exists(resources_from_aws_config_redis_key):
# This will force a refresh of our redis cache if the data exists in S3
await retrieve_json_data_from_redis_or_s3(
redis_key=resources_from_aws_config_redis_key,
s3_bucket=config.get("aws_config_cache_combined.s3.bucket"),
s3_key=config.get(
"aws_config_cache_combined.s3.file",
"aws_config_cache_combined/aws_config_resource_cache_combined_v1.json.gz",
),
redis_data_type="hash",
)
resource_info = await redis_hget(resources_from_aws_config_redis_key, arn)
if resource_info:
return json.loads(resource_info).get("accountId", "")
elif "arn:aws:s3:::" in arn:
# Try to retrieve S3 bucket information from S3 cache. This is inefficient and we should ideally have
# retrieved this info from our AWS Config cache, but we've encountered problems with AWS Config historically
# that have necessitated this code.
s3_cache = await retrieve_json_data_from_redis_or_s3(
redis_key=config.get("redis.s3_buckets_key", "S3_BUCKETS"),
redis_data_type="hash",
)
search_bucket_name = arn.split(":")[-1]
for bucket_account_id, buckets in s3_cache.items():
buckets_j = json.loads(buckets)
if search_bucket_name in buckets_j:
return bucket_account_id
return ""
async def generate_policy_name(
policy_name: str, user: str, expiration_date: Optional[int] = None
) -> str:
"""
Generate a unique policy name identifying the user and time of the change request.
:param policy_name: A predefined policy name that will override the generated one, if it exists
:param user: User's e-mail address
:return: policy name string
"""
temp_policy_prefix = config.get("policies.temp_policy_prefix", "cm_delete-on")
if policy_name:
return policy_name
user_stripped = user.split("@")[0]
random_string = await generate_random_string()
if expiration_date:
return (
f"{temp_policy_prefix}_{expiration_date}_{user_stripped}_{int(time.time())}"
)
return f"cm_{user_stripped}_{int(time.time())}_{random_string}"
async def get_url_for_resource(
arn,
resource_type=None,
account_id=None,
region=None,
resource_name=None,
resource_sub_type=None,
):
if not resource_type:
resource_type = await get_resource_type_for_arn(arn)
if not account_id:
account_id = await get_resource_account(arn)
if not region:
region = await get_region_for_arn(arn)
if not resource_name:
resource_name = await get_resource_name_for_arn(arn)
if not resource_sub_type:
resource_sub_type = await get_resource_sub_type_for_arn(arn)
# If account id is not found
if not account_id:
raise ResourceNotFound("The account for the given ARN could not be determined")
url = ""
if (
resource_type == "iam" and resource_sub_type == "role"
) or resource_type == "AWS::IAM::Role":
resource_name = arn.split("/")[-1]
url = f"/policies/edit/{account_id}/iamrole/{resource_name}"
elif (
resource_type == "iam" and resource_sub_type == "policy" and account_id != "aws"
):
url = f"/policies/edit/{account_id}/managed_policy/{resource_name}"
elif resource_type in ["s3", "AWS::S3::Bucket"]:
url = f"/policies/edit/{account_id}/s3/{resource_name}"
elif resource_type == "managed_policy":
# managed policies can have a path
resource_name_and_path = arn.split(":policy/")[-1]
url = f"/policies/edit/{account_id}/managed_policy/{resource_name_and_path}"
elif resource_type in ["sns", "AWS::SNS::Topic"]:
url = f"/policies/edit/{account_id}/sns/{region}/{resource_name}"
elif resource_type in ["sqs", "AWS::SQS::Queue"]:
url = f"/policies/edit/{account_id}/sqs/{region}/{resource_name}"
elif (resource_type == "AWS::CloudFormation::Stack") or (
resource_type == "cloudformation" and resource_sub_type == "stack"
):
url = f"/role/{account_id}?redirect=https://console.aws.amazon.com/cloudformation/home?region={region}#/stacks/"
elif resource_type == "AWS::CloudFront::Distribution" or (
resource_type == "cloudfront" and resource_sub_type == "distribution"
):
url = f"/role/{account_id}?redirect=https://console.aws.amazon.com/cloudfront/home?%23distribution-settings:{resource_name}"
elif resource_type == "AWS::CloudTrail::Trail" or (
resource_type == "cloudtrail" and resource_sub_type == "trail"
):
url = f"/role/{account_id}?redirect=https://console.aws.amazon.com/cloudtrail/home?region={region}%23/configuration"
elif resource_type == "AWS::CloudWatch::Alarm" or (
resource_type == "cloudwatch" and arn.split(":")[5] == "alarm"
):
url = (
f"/role/{account_id}?redirect=https://console.aws.amazon.com/cloudwatch/home"
f"?region={region}%23alarmsV2:"
)
elif resource_type == "AWS::CodeBuild::Project" or (
resource_type == "codebuild" and resource_sub_type == "project"
):
url = (
f"/role/{account_id}?redirect=https://console.aws.amazon.com/codesuite/codebuild/"
f"{account_id}/projects/{resource_name}/history?region={region}"
)
elif (
resource_type == "AWS::CodePipeline::Pipeline"
or resource_type == "codepipeline"
):
url = (
f"/role/{account_id}?redirect="
"https://console.aws.amazon.com/codesuite/codepipeline/pipelines/"
f"{resource_name}/view?region={region}"
)
elif resource_type == "AWS::DynamoDB::Table" or (
resource_type == "dynamodb" and resource_sub_type == "table"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/dynamodb/home?region={region}%23tables:selected={resource_name}"
)
elif resource_type == "AWS::EC2::CustomerGateway" or (
resource_type == "ec2" and resource_sub_type == "customer-gateway"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23CustomerGateways:search={resource_name}"
)
elif resource_type == "AWS::EC2::InternetGateway" or (
resource_type == "ec2" and resource_sub_type == "internet-gateway"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23igws:search={resource_name}"
)
elif resource_type == "AWS::EC2::NatGateway" or (
resource_type == "ec2" and resource_sub_type == "natgateway"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23NatGateways:search={resource_name}"
)
elif resource_type == "AWS::EC2::NetworkAcl" or (
resource_type == "ec2" and resource_sub_type == "network-acl"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23acls:search={resource_name}"
)
elif resource_type == "AWS::EC2::RouteTable" or (
resource_type == "ec2" and resource_sub_type == "route-table"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23RouteTables:search={resource_name}"
)
elif resource_type == "AWS::EC2::SecurityGroup" or (
resource_type == "ec2" and resource_sub_type == "security-group"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/ec2/v2/home?region={region}%23SecurityGroup:groupId={resource_name}"
)
elif resource_type == "AWS::EC2::Subnet" or (
resource_type == "ec2" and resource_sub_type == "subnet"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23subnets:search={resource_name}"
)
elif resource_type == "AWS::EC2::VPC" or (
resource_type == "ec2" and resource_sub_type == "vpc"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23vpcs:search={resource_name}"
)
elif resource_type == "AWS::EC2::VPCEndpoint" or (
resource_type == "ec2" and resource_sub_type == "vpc-endpoint"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23Endpoints:search={resource_name}"
)
elif resource_type == "AWS::EC2::VPCEndpointService" or (
resource_type == "ec2" and resource_sub_type == "vpc-endpoint-service"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23EndpointServices:search={resource_name}"
)
elif resource_type == "AWS::EC2::VPCPeeringConnection" or (
resource_type == "ec2" and resource_sub_type == "vpc-peering-connection"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23PeeringConnections:search={resource_name}"
)
elif resource_type == "AWS::EC2::VPNConnection" or (
resource_type == "ec2" and resource_sub_type == "vpn-connection"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23VpnConnections:search={resource_name}"
)
elif resource_type == "AWS::EC2::VPNGateway" or (
resource_type == "ec2" and resource_sub_type == "vpn-gateway"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/vpc/home?region={region}%23VpnGateways:search={resource_name}"
)
elif resource_type == "AWS::ElasticBeanstalk::Application" or (
resource_type == "elasticbeanstalk" and resource_sub_type == "application"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/elasticbeanstalk/home?region={region}%23/applications"
)
elif resource_type == "AWS::ElasticBeanstalk::ApplicationVersion" or (
resource_type == "elasticbeanstalk"
and resource_sub_type == "applicationversion"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/elasticbeanstalk/home?region={region}%23/applications"
)
elif resource_type == "AWS::ElasticBeanstalk::Environment" or (
resource_type == "elasticbeanstalk" and resource_sub_type == "environment"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/elasticbeanstalk/home?region={region}%23/environments"
)
elif resource_type == "AWS::ElasticLoadBalancing::LoadBalancer" or (
resource_type == "elasticloadbalancing"
and resource_sub_type == "loadbalancer"
and "/app/" not in arn
):
url = (
f"/role/{account_id}?redirect="
"https://console.aws.amazon.com"
f"/ec2/v2/home?region={region}%23LoadBalancers:search={resource_name}"
)
elif resource_type == "AWS::ElasticLoadBalancingV2::LoadBalancer" or (
resource_type == "elasticloadbalancing" and resource_sub_type == "loadbalancer"
):
if "/" in resource_name:
resource_name = arn.split("/")[2]
url = (
f"/role/{account_id}?redirect="
"https://console.aws.amazon.com"
f"/ec2/v2/home?region={region}%23LoadBalancers:search={resource_name}"
)
elif resource_type == "AWS::Elasticsearch::Domain" or (
resource_type == "es" and resource_sub_type == "domain"
):
url = (
f"/role/{account_id}?redirect="
"https://console.aws.amazon.com"
f"/es/home?region={region}%23domain:resource={resource_name};action=dashboard;tab=undefined"
)
elif resource_type == "AWS::Lambda::Function" or (
resource_type == "lambda" and arn.split(":")[5] == "function"
):
resource_name = arn.split(":")[6]
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/lambda/home?region={region}%23/functions/{resource_name}"
)
elif resource_type == "AWS::RDS::DBSnapshot" or (
resource_type == "rds" and arn.split(":")[5] == "snapshot"
):
resource_name = arn.split(":")[6]
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/rds/home?region={region}%23db-snapshot:id={resource_name}"
)
# TBD
elif resource_type == "AWS::Redshift::Cluster":
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/rds/home?region={region}%23db-snapshot:id={resource_name}"
)
elif resource_type == "AWS::IAM::Policy" or (
resource_type == "iam" and resource_sub_type == "policy"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/iam/home?%23/policies/{arn}$serviceLevelSummary"
)
elif resource_type == "AWS::IAM::User" or (
resource_type == "iam" and resource_sub_type == "user"
):
resource_name = arn.split("/")[-1]
url = f"/policies/edit/{account_id}/iamuser/{resource_name}"
elif resource_type == "AWS::IAM::Group" or (
resource_type == "iam" and resource_sub_type == "group"
):
url = f"/role/{account_id}?redirect=https://console.aws.amazon.com/iam/home?%23/groups/{resource_name}"
elif resource_type == "AWS::Shield::Protection":
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/wafv2/shield%23/tedx"
)
elif resource_type == "AWS::ShieldRegional::Protection" or (
resource_type == "shield" and resource_sub_type == "protection"
):
url = (
f"/role/{account_id}?redirect="
f"https://console.aws.amazon.com/wafv2/shield%23/tedx"
)
elif resource_type in ["AWS::WAF::RateBasedRule", "AWS::WAF::Rule"] or (
resource_type == "waf" and resource_sub_type in ["rule", "ratebasedrule"]
):
url = (
f"/role/{account_id}?redirect=" f"https://console.aws.amazon.com/wafv2/home"
)
elif resource_type == "AWS::WAF::RuleGroup" or (
resource_type in ["waf", "wafv2"] and "rulegroup/" in arn
):
url = (
f"/role/{account_id}?redirect=" f"https://console.aws.amazon.com/wafv2/fms"
)
elif resource_type == "AWS::WAF::WebACL" or (
resource_type in ["waf", "wafv2"] and "webacl/" in arn
):
url = (
f"/role/{account_id}?redirect=" f"https://console.aws.amazon.com/wafv2/home"
)
return url
async def generate_honeybee_request_from_change_model_array(
request_creation: RequestCreationModel, user: str, extended_request_uuid: str
) -> ExtendedRequestModel:
repositories_for_request = {}
primary_principal = None
t = int(time.time())
generated_branch_name = f"{user}-{t}"
policy_name = config.get(
"generate_honeybee_request_from_change_model_array.policy_name",
"self_service_generated",
)
repo_config = None
# Checkout Git Repo and generate a branch name for the user's change
for change in request_creation.changes.changes:
if primary_principal and change.principal != primary_principal:
raise Exception("Changes must all affect the same principal")
primary_principal = change.principal
discovered_repository_for_change = False
if repositories_for_request.get(change.principal.repository_name):
continue
# Find repo
for r in config.get("cache_resource_templates.repositories", []):
if r["name"] == change.principal.repository_name:
repo_config = r
repo = Repository(
r["repo_url"], r["name"], r["authentication_settings"]["email"]
)
await repo.clone(depth=1)
git_client = repo.git
git_client.reset()
git_client.checkout(b=generated_branch_name)
repositories_for_request[change.principal.repository_name] = {
"main_branch_name": r["main_branch_name"],
"repo": repo,
"git_client": git_client,
"config": r,
}
discovered_repository_for_change = True
break
if not discovered_repository_for_change:
raise Exception(
"No matching repository found for change in ConsoleMe's configuration"
)
request_changes = ChangeModelArray(changes=[])
affected_templates = []
for change in request_creation.changes.changes:
git_client = repositories_for_request[change.principal.repository_name][
"git_client"
]
repo = repositories_for_request[change.principal.repository_name]["repo"].repo
main_branch_name = repositories_for_request[change.principal.repository_name][
"main_branch_name"
]
git_client.checkout(
f"origin/{main_branch_name}", change.principal.resource_identifier
)
change_file_path = f"{repo.working_dir}/{change.principal.resource_identifier}"
with open(change_file_path, "r") as f:
yaml_content = yaml.load(f)
# Original
buf = io.BytesIO()
yaml.dump(yaml_content, buf)
original_text = buf.getvalue()
successfully_merged_statement = False
if not yaml_content.get("Policies"):
yaml_content["Policies"] = []
if isinstance(yaml_content["Policies"], dict):
yaml_content["Policies"] = [yaml_content["Policies"]]
# The PolicyModel is a representation of a single (usually inline) policy that a user has requested be merged
# into a given template. If the policy is provided as a string, it's the contents of the full file (which
# should include the user's requested change)
if isinstance(change.policy, PolicyModel):
if isinstance(change.policy.policy_document["Statement"], str):
change.policy.policy_document["Statement"] = [
change.policy.policy_document["Statement"]
]
for i in range(len(yaml_content.get("Policies", []))):
policy = yaml_content["Policies"][i]
if policy.get("PolicyName") != policy_name:
continue
if policy.get("IncludeAccounts") or policy.get("ExcludeAccounts"):
raise ValueError(
f"The {policy_name} policy has IncludeAccounts or ExcludeAccounts set"
)
successfully_merged_statement = True
policy["Statement"].extend(
CommentedSeq(change.policy.policy_document["Statement"])
)
yaml_content["Policies"][i][
"Statement"
] = await minimize_iam_policy_statements(
json.loads(json.dumps(policy["Statement"]))
)
if not successfully_merged_statement:
yaml_content["Policies"].append(
{
"PolicyName": policy_name,
"Statement": change.policy.policy_document["Statement"],
}
)
with open(change_file_path, "w") as f:
yaml.dump(yaml_content, f)
# New
buf = io.BytesIO()
yaml.dump(yaml_content, buf)
updated_text = buf.getvalue()
elif isinstance(change.policy, str):
# If the change is provided as a string, it represents the full change
updated_text = change.policy
with open(change_file_path, "w") as f:
f.write(updated_text)
else:
raise Exception(
"Unable to parse change from Honeybee templated role change request"
)
request_changes.changes.append(
GenericFileChangeModel(
principal=primary_principal,
action="attach",
change_type="generic_file",
policy=updated_text,
old_policy=original_text,
encoding="yaml",
)
)
git_client.add(change.principal.resource_identifier)
affected_templates.append(change.principal.resource_identifier)
pull_request_url = ""
if not request_creation.dry_run:
commit_title = f"ConsoleMe Generated PR for {', '.join(affected_templates)}"
commit_message = (
f"This request was made through ConsoleMe Self Service\n\nUser: {user}\n\n"
f"Justification: {request_creation.justification}"
)
git_client.commit(m=commit_message)
git_client.push(u=["origin", generated_branch_name])
if repo_config["code_repository_provider"] == "bitbucket":
bitbucket = BitBucket(
repo_config["code_repository_config"]["url"],
config.get(
repo_config["code_repository_config"]["username_config_key"]
),
config.get(
repo_config["code_repository_config"]["password_config_key"]
),
)
pull_request_url = await bitbucket.create_pull_request(
repo_config["project_key"],
repo_config["name"],
repo_config["project_key"],
repo_config["name"],
generated_branch_name,
repo_config["main_branch_name"],
commit_title,
commit_message,
)
else:
raise Exception(
f"Unsupported `code_repository_provider` specified in configuration: {repo_config}"
)
for repo_name, repo_details in repositories_for_request.items():
await repo_details["repo"].cleanup()
if not pull_request_url and not request_creation.dry_run:
raise Exception("Unable to generate pull request URL")
return ExtendedRequestModel(
id=extended_request_uuid,
request_url=pull_request_url,
principal=primary_principal,
timestamp=int(time.time()),
requester_email=user,
approvers=[],
request_status=RequestStatus.pending,
changes=request_changes,
requester_info=UserModel(
email=user,
extended_info=await auth.get_user_info(user),
details_url=config.config_plugin().get_employee_info_url(user),
photo_url=config.config_plugin().get_employee_photo_url(user),
),
comments=[],
cross_account=False,
)
async def get_user_details(
account_id: str, user_name: str, extended: bool = False, force_refresh: bool = False
) -> Optional[Union[ExtendedAwsPrincipalModel, AwsPrincipalModel]]:
account_ids_to_name = await get_account_id_to_name_mapping()
arn = f"arn:aws:iam::{account_id}:user/{user_name}"
user = await aws.fetch_iam_user(account_id, arn)
# requested user doesn't exist
if not user:
return None
if extended:
return ExtendedAwsPrincipalModel(
name=user_name,
account_id=account_id,
account_name=account_ids_to_name.get(account_id, None),
arn=arn,
inline_policies=user.get("UserPolicyList", []),
config_timeline_url=await get_config_timeline_url_for_role(
user, account_id
),
cloudtrail_details=await get_cloudtrail_details_for_role(arn),
s3_details=await get_s3_details_for_role(
account_id=account_id, role_name=user_name
),
apps=await get_app_details_for_role(arn),
managed_policies=user["AttachedManagedPolicies"],
groups=user["Groups"],
tags=user["Tags"],
owner=user.get("owner"),
templated=False,
template_link=None,
created_time=str(user.get("CreateDate", "")),
last_used_time=user.get("RoleLastUsed", {}).get("LastUsedDate"),
description=user.get("Description"),
permissions_boundary=user.get("PermissionsBoundary", {}),
)
else:
return AwsPrincipalModel(
name=user_name,
account_id=account_id,
account_name=account_ids_to_name.get(account_id, None),
arn=arn,
)
async def get_role_details(
account_id: str, role_name: str, extended: bool = False, force_refresh: bool = False
) -> Optional[Union[ExtendedAwsPrincipalModel, AwsPrincipalModel]]:
account_ids_to_name = await get_account_id_to_name_mapping()
arn = f"arn:aws:iam::{account_id}:role/{role_name}"
role = await aws.fetch_iam_role(account_id, arn, force_refresh=force_refresh)
# requested role doesn't exist
if not role:
return None
if extended:
template = await get_role_template(arn)
return ExtendedAwsPrincipalModel(
name=role_name,
account_id=account_id,
account_name=account_ids_to_name.get(account_id, None),
arn=arn,
inline_policies=role["policy"].get(
"RolePolicyList", role["policy"].get("UserPolicyList", [])
),
assume_role_policy_document=role["policy"]["AssumeRolePolicyDocument"],
config_timeline_url=await get_config_timeline_url_for_role(
role, account_id
),
cloudtrail_details=await get_cloudtrail_details_for_role(arn),
s3_details=await get_s3_details_for_role(
account_id=account_id, role_name=role_name
),
apps=await get_app_details_for_role(arn),
managed_policies=role["policy"]["AttachedManagedPolicies"],
tags=role["policy"]["Tags"],
templated=bool(template),
template_link=template,
created_time=role["policy"].get("CreateDate"),
last_used_time=role["policy"].get("RoleLastUsed", {}).get("LastUsedDate"),
description=role["policy"].get("Description"),
owner=role.get("owner"),
permissions_boundary=role["policy"].get("PermissionsBoundary", {}),
)
else:
return AwsPrincipalModel(
name=role_name,
account_id=account_id,
account_name=account_ids_to_name.get(account_id, None),
arn=arn,
)
class RequestStatus(Enum):
pending = "pending"
cancelled = "cancelled"
approved = "approved"
rejected = "rejected"
class Status(Enum):
applied = "applied"
not_applied = "not_applied"
cancelled = "cancelled"
class GenericFileChangeModel(ChangeModel):
principal: Optional[
Union[AwsResourcePrincipalModel, HoneybeeAwsResourceTemplatePrincipalModel]
] = None
action: Optional[Action] = None
change_type: Optional[constr(regex=r"generic_file")] = None
policy: Optional[str] = None
old_policy: Optional[str] = None
encoding: Optional[Encoding] = None
class ResourceTagChangeModel(ChangeModel):
original_key: Optional[str] = Field(
None,
description="original_key is used for renaming a key to something else. This is optional.",
example="key_to_be_renamed",
)
key: Optional[str] = Field(
None,
description="This is the desired key name for the tag. If a tag key is being renamed, this is what it will be renamed\nto. Otherwise, this key name will be used when creating or updating a tag.",
example="desired_key_name",
)
original_value: Optional[str] = None
value: Optional[str] = None
change_type: Optional[constr(regex=r"resource_tag")] = None
tag_action: TagAction
class ManagedPolicyChangeModel(ChangeModel):
arn: constr(
regex=r"(^arn:([^:]*):([^:]*):([^:]*):(|\*|[\d]{12}|cloudfront|aws):(.+)$)|^\*$"
)
change_type: Optional[constr(regex=r"managed_policy")] = None
action: Action
class PermissionsBoundaryChangeModel(ChangeModel):
arn: constr(
regex=r"(^arn:([^:]*):([^:]*):([^:]*):(|\*|[\d]{12}|cloudfront|aws):(.+)$)|^\*$"
)
change_type: Optional[constr(regex=r"permissions_boundary")] = None
action: Action
class UserModel(BaseModel):
email: Optional[str] = None
extended_info: Optional[Dict[str, Any]] = None
details_url: Optional[str] = Field(None, example="https://details_about/user")
photo_url: Optional[str] = Field(
None, example="https://user_photos/user_thumbnail.jpg"
)
class InlinePolicyChangeModel(ChangeModel):
policy_name: Optional[str] = None
new: Optional[bool] = True
action: Optional[Action] = None
change_type: Optional[constr(regex=r"inline_policy")] = None
policy: Optional[PolicyModel] = None
old_policy: Optional[PolicyModel] = None
class AssumeRolePolicyChangeModel(ChangeModel):
change_type: Optional[constr(regex=r"assume_role_policy")] = None
policy: Optional[PolicyModel] = None
old_policy: Optional[PolicyModel] = None
source_change_id: Optional[str] = Field(
None,
description="the change model ID of the source change, that this change was generated from",
)
class ManagedPolicyResourceChangeModel(ChangeModel):
new: Optional[bool] = True
change_type: Optional[constr(regex=r"managed_policy_resource")] = None
policy: Optional[PolicyModel] = None
old_policy: Optional[PolicyModel] = None
class ChangeModelArray(BaseModel):
changes: List[
Union[
InlinePolicyChangeModel,
ManagedPolicyChangeModel,
PermissionsBoundaryChangeModel,
ResourcePolicyChangeModel,
AssumeRolePolicyChangeModel,
ResourceTagChangeModel,
GenericFileChangeModel,
ManagedPolicyResourceChangeModel,
]
]
class RequestCreationModel(BaseModel):
changes: ChangeModelArray
justification: Optional[str] = None
dry_run: Optional[bool] = False
admin_auto_approve: Optional[bool] = False
class ExtendedRequestModel(RequestModel):
changes: ChangeModelArray
requester_info: UserModel
reviewer: Optional[str] = None
comments: Optional[List[CommentModel]] = None
The provided code snippet includes necessary dependencies for implementing the `generate_request_from_change_model_array` function. Write a Python function `async def generate_request_from_change_model_array( request_creation: RequestCreationModel, user: str ) -> ExtendedRequestModel` to solve the following problem:
Compiles an ChangeModelArray and returns a filled out ExtendedRequestModel based on the changes :param request_creation: ChangeModelArray :param user: Str - requester's email address :return: ChangeModelArray
Here is the function:
async def generate_request_from_change_model_array(
request_creation: RequestCreationModel, user: str
) -> ExtendedRequestModel:
"""
Compiles an ChangeModelArray and returns a filled out ExtendedRequestModel based on the changes
:param request_creation: ChangeModelArray
:param user: Str - requester's email address
:return: ChangeModelArray
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"request": request_creation.dict(),
"message": "Incoming request",
}
log.info(log_data)
primary_principal = None
change_models = request_creation.changes
if len(change_models.changes) < 1:
log_data["message"] = "At least 1 change is required to create a request."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
inline_policy_changes = []
managed_policy_changes = []
resource_policy_changes = []
assume_role_policy_changes = []
resource_tag_changes = []
permissions_boundary_changes = []
managed_policy_resource_changes = []
generic_file_changes = []
role = None
extended_request_uuid = str(uuid.uuid4())
incremental_change_id = 0
supported_resource_policies = config.get(
"policies.supported_resource_types_for_policy_application", ["s3", "sqs", "sns"]
)
for change in change_models.changes:
# All changes status must be not-applied at request creation
change.status = Status.not_applied
# Add ID for each change
change.id = extended_request_uuid + str(incremental_change_id)
incremental_change_id += 1
# Enforce a maximum of one principal ARN per ChangeGeneratorModelArray (aka Policy Request)
if not primary_principal:
primary_principal = change.principal
if primary_principal != change.principal:
log_data[
"message"
] = "We only support making changes to a single principal ARN per request."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if change.change_type == "inline_policy":
inline_policy_changes.append(
InlinePolicyChangeModel.parse_obj(change.__dict__)
)
elif change.change_type == "managed_policy":
managed_policy_changes.append(
ManagedPolicyChangeModel.parse_obj(change.__dict__)
)
elif change.change_type == "managed_policy_resource":
managed_policy_resource_changes.append(
ManagedPolicyResourceChangeModel.parse_obj(change.__dict__)
)
elif change.change_type == "resource_policy":
change.autogenerated = False
change.source_change_id = None
resource_arn_parsed = parse_arn(change.arn)
resource_type = resource_arn_parsed["service"]
if resource_type in supported_resource_policies:
change.supported = True
else:
change.supported = False
resource_policy_changes.append(change)
elif change.change_type == "assume_role_policy":
assume_role_policy_changes.append(
AssumeRolePolicyChangeModel.parse_obj(change.__dict__)
)
elif change.change_type == "resource_tag":
resource_tag_changes.append(
ResourceTagChangeModel.parse_obj(change.__dict__)
)
elif change.change_type == "permissions_boundary":
permissions_boundary_changes.append(
PermissionsBoundaryChangeModel.parse_obj(change.__dict__)
)
elif change.change_type == "generic_file":
generic_file_changes.append(
GenericFileChangeModel.parse_obj(change.__dict__)
)
else:
raise UnsupportedChangeType(
f"Invalid `change_type` for change: {change.__dict__}"
)
# Make sure the requester is only ever 64 chars with domain
if len(user) > 64:
split_items: list = user.split("@")
user: str = (
split_items[0][: (64 - (len(split_items[-1]) + 1))] + "@" + split_items[-1]
)
if primary_principal.principal_type == "AwsResource":
# TODO: Separate this out into another function
account_id = await get_resource_account(primary_principal.principal_arn)
arn_parsed = parse_arn(primary_principal.principal_arn)
arn_type = arn_parsed["service"]
arn_name = (
arn_parsed["resource_path"]
if arn_parsed["resource_path"]
else arn_parsed["resource"]
)
arn_region = arn_parsed["region"]
try:
arn_url = await get_url_for_resource(
arn=primary_principal.principal_arn,
resource_type=arn_type,
account_id=account_id,
region=arn_region,
resource_name=arn_name,
)
except ResourceNotFound:
# should never reach this case...
arn_url = ""
# Only one assume role policy change allowed per request
if len(assume_role_policy_changes) > 1:
log_data[
"message"
] = "One one assume role policy change supported per request."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if len(managed_policy_resource_changes) > 0:
# for managed policy changes, principal arn must be a managed policy
if arn_parsed["service"] != "iam" or arn_parsed["resource"] != "policy":
log_data[
"message"
] = "Principal ARN type not supported for managed policy resource changes."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if arn_parsed["account"] == "aws":
log_data["message"] = "AWS Managed Policies aren't valid for changes."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if (
len(inline_policy_changes) > 0
or len(managed_policy_changes) > 0
or len(assume_role_policy_changes) > 0
or len(permissions_boundary_changes) > 0
):
log_data[
"message"
] = "Principal ARN type not supported for inline/managed/assume role policy changes."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
if len(managed_policy_resource_changes) > 1:
log_data[
"message"
] = "One one managed policy resource change supported per request."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
policy_name = arn_parsed["resource_path"].split("/")[-1]
managed_policy_resource = None
try:
managed_policy_resource = await sync_to_async(
get_managed_policy_document
)(
policy_arn=primary_principal.principal_arn,
account_number=account_id,
assume_role=config.get("policies.role_name"),
region=config.region,
retry_max_attempts=2,
)
except ClientError as e:
if e.response["Error"]["Code"] == "NoSuchEntity":
# Could be a new managed policy, hence not found
pass
else:
log_data[
"message"
] = "Exception raised while getting managed policy"
log.error(log_data, exc_info=True)
raise InvalidRequestParameter(log_data["message"] + ": " + str(e))
for managed_policy_resource_change in managed_policy_resource_changes:
await validate_managed_policy_resource_change(
managed_policy_resource_change,
policy_name,
user,
managed_policy_resource,
)
elif (
len(inline_policy_changes) > 0
or len(managed_policy_changes) > 0
or len(assume_role_policy_changes) > 0
or len(permissions_boundary_changes) > 0
):
# for inline/managed/assume role policies, principal arn must be a role
if arn_parsed["service"] != "iam" or arn_parsed["resource"] not in [
"role",
"user",
]:
log_data[
"message"
] = "Resource not found, or ARN type not supported for inline/managed/assume role policy changes."
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
principal_name = arn_parsed["resource_path"].split("/")[-1]
principal_details = None
if arn_parsed["resource"] == "role":
principal_details = await get_role_details(
account_id, role_name=principal_name, extended=True
)
elif arn_parsed["resource"] == "user":
principal_details = await get_user_details(
account_id, user_name=principal_name, extended=True
)
if not principal_details:
log_data["message"] = "Principal not found"
log.error(log_data)
raise InvalidRequestParameter(log_data["message"])
for inline_policy_change in inline_policy_changes:
inline_policy_change.policy_name = await generate_policy_name(
inline_policy_change.policy_name,
user,
inline_policy_change.expiration_date,
)
await validate_inline_policy_change(
inline_policy_change, user, principal_details
)
for managed_policy_change in managed_policy_changes:
await validate_managed_policy_change(
managed_policy_change, user, principal_details
)
for permissions_boundary_change in permissions_boundary_changes:
await validate_permissions_boundary_change(
permissions_boundary_change, user, principal_details
)
for assume_role_policy_change in assume_role_policy_changes:
if arn_parsed["resource"] == "user":
raise UnsupportedChangeType(
"Unable to modify an assume role policy associated with an IAM user"
)
await validate_assume_role_policy_change(
assume_role_policy_change, user, principal_details
)
for resource_tag_change in resource_tag_changes:
await validate_resource_tag_change(
resource_tag_change, user, principal_details
)
# TODO: validate resource policy logic when we are ready to apply that
# If here, request is valid and can successfully be generated
request_changes = ChangeModelArray(
changes=inline_policy_changes
+ managed_policy_changes
+ resource_policy_changes
+ assume_role_policy_changes
+ resource_tag_changes
+ permissions_boundary_changes
+ managed_policy_resource_changes
)
extended_request = ExtendedRequestModel(
admin_auto_approve=request_creation.admin_auto_approve,
id=extended_request_uuid,
principal=primary_principal,
timestamp=int(time.time()),
justification=request_creation.justification,
requester_email=user,
approvers=[], # TODO: approvers logic (future feature)
request_status=RequestStatus.pending,
changes=request_changes,
requester_info=UserModel(
email=user,
extended_info=await auth.get_user_info(user),
details_url=config.config_plugin().get_employee_info_url(user),
photo_url=config.config_plugin().get_employee_photo_url(user),
),
comments=[],
cross_account=False,
arn_url=arn_url,
)
extended_request = await populate_old_policies(extended_request, user, role)
extended_request = await generate_resource_policies(extended_request, user)
if len(managed_policy_resource_changes) > 0:
await populate_old_managed_policies(extended_request, user)
elif primary_principal.principal_type == "HoneybeeAwsResourceTemplate":
# TODO: Generate extended request from HB template
extended_request = await generate_honeybee_request_from_change_model_array(
request_creation, user, extended_request_uuid
)
else:
raise Exception("Unknown principal type")
return extended_request | Compiles an ChangeModelArray and returns a filled out ExtendedRequestModel based on the changes :param request_creation: ChangeModelArray :param user: Str - requester's email address :return: ChangeModelArray |
162,084 | import asyncio
import re
import sys
import time
import uuid
from hashlib import sha256
from typing import Dict, List, Optional, Union
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from botocore.exceptions import ClientError
from cloudaux.aws.iam import get_managed_policy_document
from cloudaux.aws.sts import boto3_cached_conn
from policy_sentry.util.actions import get_service_from_action
from policy_sentry.util.arns import parse_arn
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
NoMatchingRequest,
ResourceNotFound,
Unauthorized,
UnsupportedChangeType,
)
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
create_or_update_managed_policy,
fetch_resource_details,
generate_updated_resource_policy,
get_bucket_location_with_fallback,
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_resource_policy,
get_service_from_arn,
sanitize_session_name,
)
from consoleme.lib.change_request import generate_policy_name
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.policies import (
can_move_back_to_pending_v2,
can_update_cancel_requests_v2,
get_url_for_resource,
invalid_characters_in_policy,
send_communications_new_comment,
send_communications_policy_change_request_v2,
)
from consoleme.lib.templated_resources.requests import (
generate_honeybee_request_from_change_model_array,
)
from consoleme.lib.v2.aws_principals import get_role_details, get_user_details
from consoleme.models import (
Action,
ActionResult,
ApplyChangeModificationModel,
AssumeRolePolicyChangeModel,
CancelChangeModificationModel,
ChangeModel,
ChangeModelArray,
Command,
CommentModel,
CommentRequestModificationModel,
ExtendedAwsPrincipalModel,
ExtendedRequestModel,
GenericFileChangeModel,
InlinePolicyChangeModel,
ManagedPolicyChangeModel,
ManagedPolicyResourceChangeModel,
PermissionsBoundaryChangeModel,
PolicyModel,
PolicyRequestModificationRequestModel,
PolicyRequestModificationResponseModel,
RequestCreationModel,
RequestCreationResponse,
RequestStatus,
ResourceModel,
ResourcePolicyChangeModel,
ResourceTagChangeModel,
Status,
TagAction,
UpdateChangeModificationModel,
UserModel,
)
class ExtendedRequestModel(RequestModel):
changes: ChangeModelArray
requester_info: UserModel
reviewer: Optional[str] = None
comments: Optional[List[CommentModel]] = None
async def get_request_url(extended_request: ExtendedRequestModel) -> str:
if extended_request.principal.principal_type == "AwsResource":
return f"/policies/request/{extended_request.id}"
elif extended_request.principal.principal_type == "HoneybeeAwsResourceTemplate":
return extended_request.request_url
else:
raise Exception("Unsupported principal type") | null |
162,085 | import asyncio
import re
import sys
import time
import uuid
from hashlib import sha256
from typing import Dict, List, Optional, Union
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from botocore.exceptions import ClientError
from cloudaux.aws.iam import get_managed_policy_document
from cloudaux.aws.sts import boto3_cached_conn
from policy_sentry.util.actions import get_service_from_action
from policy_sentry.util.arns import parse_arn
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
NoMatchingRequest,
ResourceNotFound,
Unauthorized,
UnsupportedChangeType,
)
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
create_or_update_managed_policy,
fetch_resource_details,
generate_updated_resource_policy,
get_bucket_location_with_fallback,
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_resource_policy,
get_service_from_arn,
sanitize_session_name,
)
from consoleme.lib.change_request import generate_policy_name
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.policies import (
can_move_back_to_pending_v2,
can_update_cancel_requests_v2,
get_url_for_resource,
invalid_characters_in_policy,
send_communications_new_comment,
send_communications_policy_change_request_v2,
)
from consoleme.lib.templated_resources.requests import (
generate_honeybee_request_from_change_model_array,
)
from consoleme.lib.v2.aws_principals import get_role_details, get_user_details
from consoleme.models import (
Action,
ActionResult,
ApplyChangeModificationModel,
AssumeRolePolicyChangeModel,
CancelChangeModificationModel,
ChangeModel,
ChangeModelArray,
Command,
CommentModel,
CommentRequestModificationModel,
ExtendedAwsPrincipalModel,
ExtendedRequestModel,
GenericFileChangeModel,
InlinePolicyChangeModel,
ManagedPolicyChangeModel,
ManagedPolicyResourceChangeModel,
PermissionsBoundaryChangeModel,
PolicyModel,
PolicyRequestModificationRequestModel,
PolicyRequestModificationResponseModel,
RequestCreationModel,
RequestCreationResponse,
RequestStatus,
ResourceModel,
ResourcePolicyChangeModel,
ResourceTagChangeModel,
Status,
TagAction,
UpdateChangeModificationModel,
UserModel,
)
log = config.get_logger()
class ExtendedRequestModel(RequestModel):
changes: ChangeModelArray
requester_info: UserModel
reviewer: Optional[str] = None
comments: Optional[List[CommentModel]] = None
The provided code snippet includes necessary dependencies for implementing the `is_request_eligible_for_auto_approval` function. Write a Python function `async def is_request_eligible_for_auto_approval( extended_request: ExtendedRequestModel, user: str ) -> bool` to solve the following problem:
Checks whether a request is eligible for auto-approval probes or not. Currently, only requests with inline_policies are eligible for auto-approval probes. :param extended_request: ExtendedRequestModel :param user: username :return bool:
Here is the function:
async def is_request_eligible_for_auto_approval(
extended_request: ExtendedRequestModel, user: str
) -> bool:
"""
Checks whether a request is eligible for auto-approval probes or not. Currently, only requests with inline_policies
are eligible for auto-approval probes.
:param extended_request: ExtendedRequestModel
:param user: username
:return bool:
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"arn": extended_request.principal.principal_arn,
"request": extended_request.dict(),
"message": "Checking whether request is eligible for auto-approval probes",
}
log.info(log_data)
is_eligible = False
# Currently the only allowances are: Inline policies
for change in extended_request.changes.changes:
# Exclude auto-generated resource policies from eligibility check
if (
change.change_type == "resource_policy"
or change.change_type == "sts_resource_policy"
) and change.autogenerated:
continue
if change.change_type != "inline_policy":
log_data[
"message"
] = "Finished checking whether request is eligible for auto-approval probes"
log_data["eligible_for_auto_approval"] = is_eligible
log.info(log_data)
return is_eligible
# If above check passes, then it's eligible for auto-approval probe check
is_eligible = True
log_data[
"message"
] = "Finished checking whether request is eligible for auto-approval probes"
log_data["eligible_for_auto_approval"] = is_eligible
log.info(log_data)
return is_eligible | Checks whether a request is eligible for auto-approval probes or not. Currently, only requests with inline_policies are eligible for auto-approval probes. :param extended_request: ExtendedRequestModel :param user: username :return bool: |
162,086 | import asyncio
import re
import sys
import time
import uuid
from hashlib import sha256
from typing import Dict, List, Optional, Union
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from botocore.exceptions import ClientError
from cloudaux.aws.iam import get_managed_policy_document
from cloudaux.aws.sts import boto3_cached_conn
from policy_sentry.util.actions import get_service_from_action
from policy_sentry.util.arns import parse_arn
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
NoMatchingRequest,
ResourceNotFound,
Unauthorized,
UnsupportedChangeType,
)
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
create_or_update_managed_policy,
fetch_resource_details,
generate_updated_resource_policy,
get_bucket_location_with_fallback,
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_resource_policy,
get_service_from_arn,
sanitize_session_name,
)
from consoleme.lib.change_request import generate_policy_name
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.policies import (
can_move_back_to_pending_v2,
can_update_cancel_requests_v2,
get_url_for_resource,
invalid_characters_in_policy,
send_communications_new_comment,
send_communications_policy_change_request_v2,
)
from consoleme.lib.templated_resources.requests import (
generate_honeybee_request_from_change_model_array,
)
from consoleme.lib.v2.aws_principals import get_role_details, get_user_details
from consoleme.models import (
Action,
ActionResult,
ApplyChangeModificationModel,
AssumeRolePolicyChangeModel,
CancelChangeModificationModel,
ChangeModel,
ChangeModelArray,
Command,
CommentModel,
CommentRequestModificationModel,
ExtendedAwsPrincipalModel,
ExtendedRequestModel,
GenericFileChangeModel,
InlinePolicyChangeModel,
ManagedPolicyChangeModel,
ManagedPolicyResourceChangeModel,
PermissionsBoundaryChangeModel,
PolicyModel,
PolicyRequestModificationRequestModel,
PolicyRequestModificationResponseModel,
RequestCreationModel,
RequestCreationResponse,
RequestStatus,
ResourceModel,
ResourcePolicyChangeModel,
ResourceTagChangeModel,
Status,
TagAction,
UpdateChangeModificationModel,
UserModel,
)
log = config.get_logger()
async def populate_cross_account_resource_policy_for_change(
change, extended_request, log_data
):
resource_policies_changed = False
supported_resource_policies = config.get(
"policies.supported_resource_types_for_policy_application", ["s3", "sqs", "sns"]
)
sts_resource_policy_supported = config.get(
"policies.sts_resource_policy_supported", True
)
supported_trust_policy_permissions = config.get(
"policies.supported_trust_policy_permissions",
[
"sts:AssumeRole",
"sts:TagSession",
"sts:AssumeRoleWithSAML",
"sts:AssumeRoleWithWebIdentity",
],
)
all_accounts = await get_account_id_to_name_mapping(status=None)
default_policy = {"Version": "2012-10-17", "Statement": []}
if change.status == Status.applied:
# Skip any changes that have already been applied so we don't overwrite any historical records
return resource_policies_changed
if (
change.change_type == "resource_policy"
or change.change_type == "sts_resource_policy"
):
# resource policy change or sts assume role policy change
resource_arn_parsed = parse_arn(change.arn)
resource_type = resource_arn_parsed["service"]
resource_name = resource_arn_parsed["resource"]
resource_region = resource_arn_parsed["region"]
resource_account = resource_arn_parsed["account"]
if not resource_account:
resource_account = await get_resource_account(change.arn)
if resource_type in supported_resource_policies:
change.supported = True
elif (
change.change_type == "sts_resource_policy"
and sts_resource_policy_supported
):
change.supported = True
else:
change.supported = False
# If we don't have resource_account (due to resource not being in Config or 3rd Party account),
# force the change to be not supported and default policy
if not resource_account:
change.supported = False
old_policy = default_policy
log_data["message"] = "Resource account couldn't be determined"
log_data["resource_arn"] = change.arn
log.warning(log_data)
elif resource_account not in all_accounts.keys():
# if we see the resource account, but it is not an account that we own
change.supported = False
old_policy = default_policy
log_data[
"message"
] = "Resource account doesn't belong to organization's accounts"
log_data["resource_arn"] = change.arn
log.warning(log_data)
else:
if change.change_type == "resource_policy":
old_policy = await get_resource_policy(
account=resource_account,
resource_type=resource_type,
name=resource_name,
region=resource_region,
)
else:
role_name = resource_arn_parsed["resource_path"].split("/")[-1]
role = await get_role_details(
resource_account,
role_name=role_name,
extended=True,
force_refresh=True,
)
if not role:
log.error(
{
**log_data,
"message": (
"Unable to retrieve role. Won't attempt to make cross-account policy."
),
}
)
return
old_policy = role.assume_role_policy_document
old_policy_sha256 = sha256(
json.dumps(old_policy, escape_forward_slashes=False).encode()
).hexdigest()
if change.old_policy and old_policy_sha256 == change.old_policy.policy_sha256:
# Old policy hasn't changed since last refresh of page, no need to generate resource policy again
return
# Otherwise it has changed
resource_policies_changed = True
change.old_policy = PolicyModel(
policy_sha256=old_policy_sha256, policy_document=old_policy
)
if not change.autogenerated:
# Change is not autogenerated (user submitted or modified), don't auto-generate
return resource_policies_changed
# Have to grab the actions from the source inline change for resource policy changes
actions = []
resource_arns = []
for source_change in extended_request.changes.changes:
# Find the specific inline policy associated with this change
if (
source_change.change_type == "inline_policy"
and source_change.id == change.source_change_id
):
for statement in source_change.policy.policy_document.get(
"Statement", []
):
# Find the specific statement within the inline policy associated with this resource
if change.arn in statement.get("Resource"):
statement_actions = statement.get("Action", [])
statement_actions = (
statement_actions
if isinstance(statement_actions, list)
else [statement_actions]
)
for action in statement_actions:
if action.startswith(f"{resource_type}:") or (
resource_type == "iam" and action.startswith("sts")
):
if change.change_type == "sts_resource_policy":
# only supported actions allowed for sts resource policy
if action in supported_trust_policy_permissions:
actions.append(action)
else:
actions.append(action)
for resource in statement.get("Resource"):
if change.arn in resource:
resource_arns.append(resource)
new_policy = await generate_updated_resource_policy(
existing=old_policy,
principal_arn=extended_request.principal.principal_arn,
resource_arns=list(set(resource_arns)),
actions=actions,
# since iam assume role policy documents can't include resources
include_resources=change.change_type == "resource_policy",
)
new_policy_sha256 = sha256(
json.dumps(new_policy, escape_forward_slashes=False).encode()
).hexdigest()
change.policy = PolicyModel(
policy_sha256=new_policy_sha256, policy_document=new_policy
)
return resource_policies_changed
class ExtendedRequestModel(RequestModel):
changes: ChangeModelArray
requester_info: UserModel
reviewer: Optional[str] = None
comments: Optional[List[CommentModel]] = None
The provided code snippet includes necessary dependencies for implementing the `populate_cross_account_resource_policies` function. Write a Python function `async def populate_cross_account_resource_policies( extended_request: ExtendedRequestModel, user: str ) -> Dict` to solve the following problem:
Populates the cross-account resource policies for supported resources for each inline policy. :param extended_request: ExtendedRequestModel :param user: username :return: Dict: changed: whether the resource policies have changed or not extended_request: modified extended_request
Here is the function:
async def populate_cross_account_resource_policies(
extended_request: ExtendedRequestModel, user: str
) -> Dict:
"""
Populates the cross-account resource policies for supported resources for each inline policy.
:param extended_request: ExtendedRequestModel
:param user: username
:return: Dict:
changed: whether the resource policies have changed or not
extended_request: modified extended_request
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"arn": extended_request.principal.principal_arn,
"request": extended_request.dict(),
"message": "Populating cross-account resource policies",
}
log.debug(log_data)
concurrent_tasks = []
for change in extended_request.changes.changes:
concurrent_tasks.append(
populate_cross_account_resource_policy_for_change(
change, extended_request, log_data
)
)
concurrent_tasks_results = await asyncio.gather(*concurrent_tasks)
resource_policies_changed = bool(any(concurrent_tasks_results))
log_data["message"] = "Done populating cross account resource policies"
log_data["request"] = extended_request.dict()
log_data["resource_policies_changed"] = resource_policies_changed
log.debug(log_data)
return {"changed": resource_policies_changed, "extended_request": extended_request} | Populates the cross-account resource policies for supported resources for each inline policy. :param extended_request: ExtendedRequestModel :param user: username :return: Dict: changed: whether the resource policies have changed or not extended_request: modified extended_request |
162,087 | import asyncio
import re
import sys
import time
import uuid
from hashlib import sha256
from typing import Dict, List, Optional, Union
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from botocore.exceptions import ClientError
from cloudaux.aws.iam import get_managed_policy_document
from cloudaux.aws.sts import boto3_cached_conn
from policy_sentry.util.actions import get_service_from_action
from policy_sentry.util.arns import parse_arn
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
NoMatchingRequest,
ResourceNotFound,
Unauthorized,
UnsupportedChangeType,
)
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
create_or_update_managed_policy,
fetch_resource_details,
generate_updated_resource_policy,
get_bucket_location_with_fallback,
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_resource_policy,
get_service_from_arn,
sanitize_session_name,
)
from consoleme.lib.change_request import generate_policy_name
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.policies import (
can_move_back_to_pending_v2,
can_update_cancel_requests_v2,
get_url_for_resource,
invalid_characters_in_policy,
send_communications_new_comment,
send_communications_policy_change_request_v2,
)
from consoleme.lib.templated_resources.requests import (
generate_honeybee_request_from_change_model_array,
)
from consoleme.lib.v2.aws_principals import get_role_details, get_user_details
from consoleme.models import (
Action,
ActionResult,
ApplyChangeModificationModel,
AssumeRolePolicyChangeModel,
CancelChangeModificationModel,
ChangeModel,
ChangeModelArray,
Command,
CommentModel,
CommentRequestModificationModel,
ExtendedAwsPrincipalModel,
ExtendedRequestModel,
GenericFileChangeModel,
InlinePolicyChangeModel,
ManagedPolicyChangeModel,
ManagedPolicyResourceChangeModel,
PermissionsBoundaryChangeModel,
PolicyModel,
PolicyRequestModificationRequestModel,
PolicyRequestModificationResponseModel,
RequestCreationModel,
RequestCreationResponse,
RequestStatus,
ResourceModel,
ResourcePolicyChangeModel,
ResourceTagChangeModel,
Status,
TagAction,
UpdateChangeModificationModel,
UserModel,
)
log = config.get_logger()
class ActionResult(BaseModel):
status: Optional[str] = None
message: Optional[str] = None
class PolicyRequestModificationResponseModel(BaseModel):
errors: Optional[int] = None
action_results: Optional[List[ActionResult1]] = None
async def _add_error_to_response(
log_data: Dict,
response: PolicyRequestModificationResponseModel,
message: str,
error=None,
):
log_data["message"] = message
log_data["error"] = error
log.error(log_data)
response.errors += 1
response.action_results.append(
ActionResult(status="error", message=log_data["message"])
)
return response | null |
162,088 | import asyncio
import re
import sys
import time
import uuid
from hashlib import sha256
from typing import Dict, List, Optional, Union
import sentry_sdk
import ujson as json
from asgiref.sync import sync_to_async
from botocore.exceptions import ClientError
from cloudaux.aws.iam import get_managed_policy_document
from cloudaux.aws.sts import boto3_cached_conn
from policy_sentry.util.actions import get_service_from_action
from policy_sentry.util.arns import parse_arn
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
NoMatchingRequest,
ResourceNotFound,
Unauthorized,
UnsupportedChangeType,
)
from consoleme.lib.account_indexers import get_account_id_to_name_mapping
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
create_or_update_managed_policy,
fetch_resource_details,
generate_updated_resource_policy,
get_bucket_location_with_fallback,
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_resource_policy,
get_service_from_arn,
sanitize_session_name,
)
from consoleme.lib.change_request import generate_policy_name
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.policies import (
can_move_back_to_pending_v2,
can_update_cancel_requests_v2,
get_url_for_resource,
invalid_characters_in_policy,
send_communications_new_comment,
send_communications_policy_change_request_v2,
)
from consoleme.lib.templated_resources.requests import (
generate_honeybee_request_from_change_model_array,
)
from consoleme.lib.v2.aws_principals import get_role_details, get_user_details
from consoleme.models import (
Action,
ActionResult,
ApplyChangeModificationModel,
AssumeRolePolicyChangeModel,
CancelChangeModificationModel,
ChangeModel,
ChangeModelArray,
Command,
CommentModel,
CommentRequestModificationModel,
ExtendedAwsPrincipalModel,
ExtendedRequestModel,
GenericFileChangeModel,
InlinePolicyChangeModel,
ManagedPolicyChangeModel,
ManagedPolicyResourceChangeModel,
PermissionsBoundaryChangeModel,
PolicyModel,
PolicyRequestModificationRequestModel,
PolicyRequestModificationResponseModel,
RequestCreationModel,
RequestCreationResponse,
RequestStatus,
ResourceModel,
ResourcePolicyChangeModel,
ResourceTagChangeModel,
Status,
TagAction,
UpdateChangeModificationModel,
UserModel,
)
log = config.get_logger()
auth = get_plugin_by_name(config.get("plugins.auth", "default_auth"))()
aws = get_plugin_by_name(config.get("plugins.aws", "default_aws"))()
async def apply_changes_to_role(
extended_request: ExtendedRequestModel,
response: Union[RequestCreationResponse, PolicyRequestModificationResponseModel],
user: str,
specific_change_id: str = None,
) -> None:
"""
Applies changes based on the changes array in the request, in a best effort manner to a role
Caution: this method applies changes blindly... meaning it assumes before calling this method,
you have validated the changes being made are authorized.
:param extended_request: ExtendedRequestModel
:param user: Str - requester's email address
:param response: RequestCreationResponse
:param specific_change_id: if this function is being used to apply only one specific change
if not provided, all non-autogenerated, supported changes are applied
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"request": extended_request.dict(),
"message": "Applying request changes",
"specific_change_id": specific_change_id,
}
log.info(log_data)
arn_parsed = parse_arn(extended_request.principal.principal_arn)
# Principal ARN must be a role for this function
if arn_parsed["service"] != "iam" or arn_parsed["resource"] not in ["role", "user"]:
log_data[
"message"
] = "Resource not found, or ARN type not supported for inline/managed/assume role policy changes."
log.error(log_data)
response.errors += 1
response.action_results.append(
ActionResult(status="error", message=log_data["message"])
)
return
principal_name = arn_parsed["resource_path"].split("/")[-1]
account_id = await get_resource_account(extended_request.principal.principal_arn)
iam_client = await sync_to_async(boto3_cached_conn)(
"iam",
service_type="client",
account_number=account_id,
region=config.region,
assume_role=config.get("policies.role_name"),
session_name=sanitize_session_name("principal-updater-" + user),
retry_max_attempts=2,
sts_client_kwargs=dict(
region_name=config.region,
endpoint_url=config.get(
"aws.sts_endpoint_url", "https://sts.{region}.amazonaws.com"
).format(region=config.region),
),
client_kwargs=config.get("boto3.client_kwargs", {}),
)
for change in extended_request.changes.changes:
if change.status == Status.applied:
# This change has already been applied, this can happen in the future when we have a multi-change request
# that an admin approves, and it applies 5 of the changes, but fails to apply 1 change due to an error.
# Upon correcting the error, the admin can click approve again, and it will only apply the changes that
# haven't already been applied
log_data[
"message"
] = "Change has already been applied, skipping applying the change"
log_data["change"] = change.dict()
log.debug(log_data)
continue
if specific_change_id and change.id != specific_change_id:
continue
if change.change_type == "inline_policy":
if change.action == Action.attach:
try:
if arn_parsed["resource"] == "role":
await sync_to_async(iam_client.put_role_policy)(
RoleName=principal_name,
PolicyName=change.policy_name,
PolicyDocument=json.dumps(
change.policy.policy_document,
escape_forward_slashes=False,
),
)
elif arn_parsed["resource"] == "user":
await sync_to_async(iam_client.put_user_policy)(
UserName=principal_name,
PolicyName=change.policy_name,
PolicyDocument=json.dumps(
change.policy.policy_document,
escape_forward_slashes=False,
),
)
response.action_results.append(
ActionResult(
status="success",
message=(
f"Successfully applied inline policy {change.policy_name} to principal: "
f"{principal_name}"
),
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred applying inline policy"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=(
f"Error occurred applying inline policy {change.policy_name} to principal: "
f"{principal_name}: " + str(e)
),
)
)
elif change.action == Action.detach:
try:
if arn_parsed["resource"] == "role":
await sync_to_async(iam_client.delete_role_policy)(
RoleName=principal_name, PolicyName=change.policy_name
)
elif arn_parsed["resource"] == "user":
await sync_to_async(iam_client.delete_user_policy)(
UserName=principal_name, PolicyName=change.policy_name
)
response.action_results.append(
ActionResult(
status="success",
message=(
f"Successfully deleted inline policy {change.policy_name} from principal: "
f"{principal_name}"
),
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred deleting inline policy"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=(
f"Error occurred deleting inline policy {change.policy_name} from principal: "
f"{principal_name} " + str(e)
),
)
)
elif change.change_type == "permissions_boundary":
if change.action == Action.attach:
try:
if arn_parsed["resource"] == "role":
await sync_to_async(iam_client.put_role_permissions_boundary)(
RoleName=principal_name, PermissionsBoundary=change.arn
)
elif arn_parsed["resource"] == "user":
await sync_to_async(iam_client.put_user_permissions_boundary)(
UserName=principal_name, PermissionsBoundary=change.arn
)
response.action_results.append(
ActionResult(
status="success",
message=(
f"Successfully attached permissions boundary {change.arn} to principal: "
f"{principal_name}"
),
)
)
change.status = Status.applied
except Exception as e:
log_data[
"message"
] = "Exception occurred attaching permissions boundary"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=(
f"Error occurred attaching permissions boundary {change.arn} to principal: "
f"{principal_name}: " + str(e)
),
)
)
elif change.action == Action.detach:
try:
if arn_parsed["resource"] == "role":
await sync_to_async(
iam_client.delete_role_permissions_boundary
)(RoleName=principal_name)
elif arn_parsed["resource"] == "user":
await sync_to_async(
iam_client.delete_user_permissions_boundary
)(UserName=principal_name)
response.action_results.append(
ActionResult(
status="success",
message=(
f"Successfully detached permissions boundary {change.arn} from principal: "
f"{principal_name}"
),
)
)
change.status = Status.applied
except Exception as e:
log_data[
"message"
] = "Exception occurred detaching permissions boundary"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=(
f"Error occurred detaching permissions boundary {change.arn} "
f"from principal: {principal_name}: " + str(e)
),
)
)
elif change.change_type == "managed_policy":
if change.action == Action.attach:
try:
if arn_parsed["resource"] == "role":
await sync_to_async(iam_client.attach_role_policy)(
RoleName=principal_name, PolicyArn=change.arn
)
elif arn_parsed["resource"] == "user":
await sync_to_async(iam_client.attach_user_policy)(
UserName=principal_name, PolicyArn=change.arn
)
response.action_results.append(
ActionResult(
status="success",
message=(
f"Successfully attached managed policy {change.arn} to principal: {principal_name}"
),
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred attaching managed policy"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=(
f"Error occurred attaching managed policy {change.arn} to principal: "
"{principal_name}: " + str(e)
),
)
)
elif change.action == Action.detach:
try:
if arn_parsed["resource"] == "role":
await sync_to_async(iam_client.detach_role_policy)(
RoleName=principal_name, PolicyArn=change.arn
)
elif arn_parsed["resource"] == "user":
await sync_to_async(iam_client.detach_user_policy)(
UserName=principal_name, PolicyArn=change.arn
)
response.action_results.append(
ActionResult(
status="success",
message=(
f"Successfully detached managed policy {change.arn} from principal: {principal_name}"
),
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred detaching managed policy"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=(
f"Error occurred detaching managed policy {change.arn} from principal: "
f"{principal_name}: " + str(e)
),
)
)
elif change.change_type == "assume_role_policy":
if arn_parsed["resource"] == "user":
raise UnsupportedChangeType(
"IAM users don't have assume role policies. Unable to process request."
)
try:
await sync_to_async(iam_client.update_assume_role_policy)(
RoleName=principal_name,
PolicyDocument=json.dumps(
change.policy.policy_document, escape_forward_slashes=False
),
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully updated assume role policy for principal: {principal_name}",
)
)
change.status = Status.applied
except Exception as e:
log_data[
"message"
] = "Exception occurred updating assume role policy policy"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred updating assume role policy for principal: {principal_name}: "
+ str(e),
)
)
elif change.change_type == "resource_tag":
if change.tag_action in [TagAction.create, TagAction.update]:
if change.original_key and not change.key:
change.key = change.original_key
if change.original_value and not change.value:
change.value = change.original_value
try:
if arn_parsed["resource"] == "role":
await sync_to_async(iam_client.tag_role)(
RoleName=principal_name,
Tags=[{"Key": change.key, "Value": change.value}],
)
elif arn_parsed["resource"] == "user":
await sync_to_async(iam_client.tag_user)(
UserName=principal_name,
Tags=[{"Key": change.key, "Value": change.value}],
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully created or updated tag for principal: {principal_name}",
)
)
if change.original_key and change.original_key != change.key:
if arn_parsed["resource"] == "role":
await sync_to_async(iam_client.untag_role)(
RoleName=principal_name, TagKeys=[change.original_key]
)
elif arn_parsed["resource"] == "user":
await sync_to_async(iam_client.untag_user)(
UserName=principal_name, TagKeys=[change.original_key]
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully renamed tag {change.original_key} to {change.key}.",
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred creating or updating tag"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred updating tag for principal: {principal_name}: "
+ str(e),
)
)
if change.tag_action == TagAction.delete:
try:
if arn_parsed["resource"] == "role":
await sync_to_async(iam_client.untag_role)(
RoleName=principal_name, TagKeys=[change.key]
)
elif arn_parsed["resource"] == "user":
await sync_to_async(iam_client.untag_user)(
UserName=principal_name, TagKeys=[change.key]
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully deleted tag for principal: {principal_name}",
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred deleting tag"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred deleting tag for principal: {principal_name}: "
+ str(e),
)
)
else:
# unsupported type for auto-application
if change.autogenerated and extended_request.admin_auto_approve:
# If the change was auto-generated and an administrator auto-approved the choices, there's no need
# to try to apply the auto-generated policies.
pass
else:
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred applying: Change type {change.change_type} is not supported",
)
)
response.errors += 1
log_data["message"] = "Unsupported type for auto-application detected"
log_data["change"] = change.dict()
log.error(log_data)
log_data["message"] = "Finished applying request changes"
log_data["request"] = extended_request.dict()
log_data["response"] = response.dict()
log.info(log_data)
async def populate_old_policies(
extended_request: ExtendedRequestModel,
user: str,
principal: Optional[ExtendedAwsPrincipalModel] = None,
) -> ExtendedRequestModel:
"""
Populates the old policies for each inline policy.
Note: Currently only applicable when the principal ARN is a role and for old inline_policies, assume role policy
:param extended_request: ExtendedRequestModel
:param user: username
:return ExtendedRequestModel
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"principal": extended_request.principal,
"request": extended_request.dict(),
"message": "Populating old policies",
}
log.debug(log_data)
if extended_request.principal.principal_type == "AwsResource":
principal_arn = extended_request.principal.principal_arn
role_account_id = await get_resource_account(principal_arn)
arn_parsed = parse_arn(principal_arn)
if arn_parsed["service"] != "iam" or arn_parsed["resource"] not in [
"role",
"user",
]:
log_data[
"message"
] = "ARN type not supported for populating old policy changes."
log.debug(log_data)
return extended_request
principal_name = arn_parsed["resource_path"].split("/")[-1]
if not principal:
if arn_parsed["resource"] == "role":
principal = await get_role_details(
role_account_id,
role_name=principal_name,
extended=True,
force_refresh=True,
)
elif arn_parsed["resource"] == "user":
principal = await get_user_details(
role_account_id,
user_name=principal_name,
extended=True,
force_refresh=True,
)
for change in extended_request.changes.changes:
if change.status == Status.applied:
# Skip changing any old policies that are saved for historical record (already applied)
continue
if change.change_type == "assume_role_policy":
change.old_policy = PolicyModel(
policy_sha256=sha256(
json.dumps(
principal.assume_role_policy_document,
escape_forward_slashes=False,
).encode()
).hexdigest(),
policy_document=principal.assume_role_policy_document,
)
elif change.change_type == "inline_policy" and not change.new:
for existing_policy in principal.inline_policies:
if change.policy_name == existing_policy.get("PolicyName"):
change.old_policy = PolicyModel(
policy_sha256=sha256(
json.dumps(
existing_policy.get("PolicyDocument"),
escape_forward_slashes=False,
).encode()
).hexdigest(),
policy_document=existing_policy.get("PolicyDocument"),
)
break
log_data["message"] = "Done populating old policies"
log_data["request"] = extended_request.dict()
log.debug(log_data)
return extended_request
async def apply_managed_policy_resource_tag_change(
extended_request: ExtendedRequestModel,
change: ResourceTagChangeModel,
response: PolicyRequestModificationResponseModel,
user: str,
) -> PolicyRequestModificationResponseModel:
"""
Applies resource tagging changes for managed policies
Caution: this method applies changes blindly... meaning it assumes before calling this method,
you have validated the changes being made are authorized.
:param change: ResourcePolicyChangeModel
:param extended_request: ExtendedRequestModel
:param user: Str - requester's email address
:param response: RequestCreationResponse
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"change": change.dict(),
"message": "Applying resource policy change changes",
"request": extended_request.dict(),
}
resource_arn_parsed = parse_arn(change.principal.principal_arn)
resource_type = resource_arn_parsed["service"]
resource_name = resource_arn_parsed["resource"]
resource_account = resource_arn_parsed["account"]
if not resource_account:
resource_account = await get_resource_account(change.principal.principal_arn)
if not resource_account:
# If we don't have resource_account (due to resource not being in Config or 3rd Party account),
# we can't apply this change
log_data["message"] = "Resource account not found"
log.warning(log_data)
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Cannot apply change to {change.principal.json()} as cannot determine resource account",
)
)
return response
if resource_type != "iam" or resource_name != "policy" or resource_account == "aws":
# Not a managed policy, or a managed policy that is AWS owned
log_data["message"] = "Resource change not supported"
log.warning(log_data)
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Cannot apply change to {change.principal.json()} as it's not supported",
)
)
return response
iam_client = await sync_to_async(boto3_cached_conn)(
"iam",
service_type="client",
account_number=resource_account,
region=config.region,
assume_role=config.get("policies.role_name"),
session_name=sanitize_session_name("tag-updater-" + user),
retry_max_attempts=2,
sts_client_kwargs=dict(
region_name=config.region,
endpoint_url=config.get(
"aws.sts_endpoint_url", "https://sts.{region}.amazonaws.com"
).format(region=config.region),
),
client_kwargs=config.get("boto3.client_kwargs", {}),
)
principal_arn = change.principal.principal_arn
if change.tag_action in [TagAction.create, TagAction.update]:
if change.original_key and not change.key:
change.key = change.original_key
if change.original_value and not change.value:
change.value = change.original_value
try:
await sync_to_async(iam_client.tag_policy)(
PolicyArn=principal_arn,
Tags=[{"Key": change.key, "Value": change.value}],
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully created or updated tag for managed policy: {principal_arn}",
)
)
if change.original_key and change.original_key != change.key:
await sync_to_async(iam_client.untag_policy)(
PolicyArn=principal_arn, TagKeys=[change.original_key]
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully renamed tag {change.original_key} to {change.key}.",
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred creating or updating tag"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred updating tag for managed policy: {principal_arn}: "
+ str(e),
)
)
elif change.tag_action == TagAction.delete:
try:
await sync_to_async(iam_client.untag_policy)(
PolicyArn=principal_arn, TagKeys=[change.key]
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully deleted tag for managed policy: {principal_arn}",
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred deleting tag"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred deleting tag for managed policy: {principal_arn}: "
+ str(e),
)
)
else:
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Unsupport change requested for tag {change.tag_action}",
)
)
return response
async def apply_non_iam_resource_tag_change(
extended_request: ExtendedRequestModel,
change: ResourceTagChangeModel,
response: PolicyRequestModificationResponseModel,
user: str,
) -> PolicyRequestModificationResponseModel:
"""
Applies resource tagging changes for supported non IAM role tags
Caution: this method applies changes blindly... meaning it assumes before calling this method,
you have validated the changes being made are authorized.
:param change: ResourcePolicyChangeModel
:param extended_request: ExtendedRequestModel
:param user: Str - requester's email address
:param response: RequestCreationResponse
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"change": change.dict(),
"message": "Applying resource policy change changes",
"request": extended_request.dict(),
}
resource_arn_parsed = parse_arn(change.principal.principal_arn)
resource_type = resource_arn_parsed["service"]
resource_name = resource_arn_parsed["resource"]
resource_region = resource_arn_parsed["region"]
resource_account = resource_arn_parsed["account"]
if not resource_account:
resource_account = await get_resource_account(change.principal.principal_arn)
if resource_type == "s3" and not resource_region:
resource_region = await get_bucket_location_with_fallback(
resource_name, resource_account
)
if not resource_account:
# If we don't have resource_account (due to resource not being in Config or 3rd Party account),
# we can't apply this change
log_data["message"] = "Resource account not found"
log.warning(log_data)
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Cannot apply change to {change.principal.json()} as cannot determine resource account",
)
)
return response
supported_resource_types = config.get(
"policies.supported_resource_types_for_policy_application", ["s3", "sqs", "sns"]
)
if resource_type not in supported_resource_types:
log_data["message"] = "Resource change not supported"
log.warning(log_data)
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Cannot apply change to {change.principal.json()} as it's not supported",
)
)
return response
try:
client = await sync_to_async(boto3_cached_conn)(
resource_type,
service_type="client",
future_expiration_minutes=15,
account_number=resource_account,
assume_role=config.get("policies.role_name"),
region=resource_region or config.region,
session_name=sanitize_session_name("apply-resource-tag-" + user),
arn_partition="aws",
sts_client_kwargs=dict(
region_name=config.region,
endpoint_url=config.get(
"aws.sts_endpoint_url", "https://sts.{region}.amazonaws.com"
).format(region=config.region),
),
client_kwargs=config.get("boto3.client_kwargs", {}),
retry_max_attempts=2,
)
resource_details = await fetch_resource_details(
resource_account,
resource_type,
resource_name,
resource_region or config.region,
)
if change.original_key and not change.key:
change.key = change.original_key
if change.original_value and not change.value:
change.value = change.original_value
if resource_type == "s3":
if change.tag_action in [TagAction.create, TagAction.update]:
tag_key_preexists = False
resulting_tagset = []
for tag in resource_details["TagSet"]:
# If we renamed a tag key, let's "skip" the tag with the original name
if change.original_key and change.original_key != change.key:
if tag.get("Key") == change.original_key:
continue
if change.key == tag["Key"]:
tag_key_preexists = True
# If we changed the value of an existing tag, let's record that
resulting_tagset.append(
{"Key": change.key, "Value": change.value}
)
else:
# Leave original tag unmodified
resulting_tagset.append(tag)
# Let's create the tag if it is a new one
if not tag_key_preexists:
resulting_tagset.append({"Key": change.key, "Value": change.value})
await sync_to_async(client.put_bucket_tagging)(
Bucket=resource_name,
Tagging={"TagSet": resulting_tagset},
)
elif change.tag_action == TagAction.delete:
resulting_tagset = []
for tag in resource_details["TagSet"]:
if tag.get("Key") != change.key:
resulting_tagset.append(tag)
resource_details["TagSet"] = resulting_tagset
await sync_to_async(client.put_bucket_tagging)(
Bucket=resource_name,
Tagging={"TagSet": resource_details["TagSet"]},
)
elif resource_type == "sns":
if change.tag_action in [TagAction.create, TagAction.update]:
await sync_to_async(client.tag_resource)(
ResourceArn=change.principal.principal_arn,
Tags=[{"Key": change.key, "Value": change.value}],
)
# Renaming a key
if change.original_key and change.original_key != change.key:
await sync_to_async(client.untag_resource)(
ResourceArn=change.principal.principal_arn,
TagKeys=[change.original_key],
)
elif change.tag_action == TagAction.delete:
await sync_to_async(client.untag_resource)(
ResourceArn=change.principal.principal_arn,
TagKeys=[change.key],
)
elif resource_type == "sqs":
if change.tag_action in [TagAction.create, TagAction.update]:
await sync_to_async(client.tag_queue)(
QueueUrl=resource_details["QueueUrl"],
Tags={change.key: change.value},
)
# Renaming a key
if change.original_key and change.original_key != change.key:
await sync_to_async(client.untag_queue)(
QueueUrl=resource_details["QueueUrl"],
TagKeys=[change.original_key],
)
elif change.tag_action == TagAction.delete:
await sync_to_async(client.untag_queue)(
QueueUrl=resource_details["QueueUrl"], TagKeys=[change.key]
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully updated resource policy for {change.principal.principal_arn}",
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception changing resource tags"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred changing resource tags for {change.principal.principal_arn}"
+ str(e),
)
)
log_data["message"] = "Finished applying resource tagging change"
log_data["response"] = response.dict()
log_data["request"] = extended_request.dict()
log_data["change"] = change.dict()
log.debug(log_data)
return response
async def apply_managed_policy_resource_change(
extended_request: ExtendedRequestModel,
change: ManagedPolicyResourceChangeModel,
response: PolicyRequestModificationResponseModel,
user: str,
) -> PolicyRequestModificationResponseModel:
"""
Applies resource policy change for managed policies
Caution: this method applies changes blindly... meaning it assumes before calling this method,
you have validated the changes being made are authorized.
:param change: ResourcePolicyChangeModel
:param extended_request: ExtendedRequestModel
:param user: Str - requester's email address
:param response: RequestCreationResponse
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"change": change.dict(),
"message": "Applying managed policy resource change",
"request": extended_request.dict(),
}
log.info(log_data)
arn_parsed = parse_arn(extended_request.principal.principal_arn)
resource_type = arn_parsed["service"]
resource_name = arn_parsed["resource"]
resource_account = arn_parsed["account"]
if resource_type != "iam" or resource_name != "policy" or resource_account == "aws":
log_data[
"message"
] = "ARN type not supported for managed policy resource changes."
log.error(log_data)
response.errors += 1
response.action_results.append(
ActionResult(status="error", message=log_data["message"])
)
return response
if not resource_account:
# If we don't have resource_account (due to resource not being in Config or 3rd Party account),
# we can't apply this change
log_data["message"] = "Resource account not found"
log.warning(log_data)
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Cannot apply change to {extended_request.principal.principal_arn} as cannot determine resource account",
)
)
return response
conn_details = {
"account_number": resource_account,
"assume_role": config.get("policies.role_name"),
"session_name": f"ConsoleMe_MP_{user}",
"client_kwargs": config.get("boto3.client_kwargs", {}),
}
# Save current policy by populating "old" policies at the time of application for historical record
populate_old_managed_policies_results = await populate_old_managed_policies(
extended_request, user
)
if populate_old_managed_policies_results["changed"]:
extended_request = populate_old_managed_policies_results["extended_request"]
policy_name = arn_parsed["resource_path"].split("/")[-1]
if change.new:
description = f"Managed Policy created using ConsoleMe by {user}"
# create new policy
try:
policy_path = "/" + arn_parsed["resource_path"].replace(policy_name, "")
await create_or_update_managed_policy(
new_policy=change.policy.policy_document,
policy_name=policy_name,
policy_arn=extended_request.principal.principal_arn,
description=description,
policy_path=policy_path,
**conn_details,
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully created managed policy {extended_request.principal.principal_arn}",
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred creating managed policy"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred creating managed policy: {str(e)}",
)
)
else:
try:
await create_or_update_managed_policy(
new_policy=change.policy.policy_document,
policy_name=policy_name,
policy_arn=extended_request.principal.principal_arn,
description="",
existing_policy=True,
**conn_details,
)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully updated managed policy {extended_request.principal.principal_arn}",
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred updating managed policy"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred creating updating policy: {str(e)}",
)
)
return response
async def apply_resource_policy_change(
extended_request: ExtendedRequestModel,
change: ResourcePolicyChangeModel,
response: PolicyRequestModificationResponseModel,
user: str,
) -> PolicyRequestModificationResponseModel:
"""
Applies resource policy change for supported changes
Caution: this method applies changes blindly... meaning it assumes before calling this method,
you have validated the changes being made are authorized.
:param change: ResourcePolicyChangeModel
:param extended_request: ExtendedRequestModel
:param user: Str - requester's email address
:param response: RequestCreationResponse
"""
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"change": change.dict(),
"message": "Applying resource policy change changes",
"request": extended_request.dict(),
}
log.info(log_data)
resource_arn_parsed = parse_arn(change.arn)
resource_type = resource_arn_parsed["service"]
resource_name = resource_arn_parsed["resource"]
resource_region = resource_arn_parsed["region"]
resource_account = resource_arn_parsed["account"]
if not resource_account:
resource_account = await get_resource_account(change.arn)
if resource_type == "s3" and not resource_region:
resource_region = await get_bucket_location_with_fallback(
resource_name, resource_account
)
if not resource_account:
# If we don't have resource_account (due to resource not being in Config or 3rd Party account),
# we can't apply this change
log_data["message"] = "Resource account not found"
log.warning(log_data)
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Cannot apply change to {change.arn} as cannot determine resource account",
)
)
return response
supported_resource_types = config.get(
"policies.supported_resource_types_for_policy_application", ["s3", "sqs", "sns"]
)
sts_resource_policy_supported = config.get(
"policies.sts_resource_policy_supported", True
)
if (
not change.supported
or (
change.change_type == "resource_policy"
and resource_type not in supported_resource_types
)
or (
change.change_type == "sts_resource_policy"
and not sts_resource_policy_supported
)
):
log_data["message"] = "Resource change not supported"
log.warning(log_data)
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Cannot apply change to {change.arn} as it's not supported",
)
)
return response
try:
client = await sync_to_async(boto3_cached_conn)(
resource_type,
service_type="client",
future_expiration_minutes=15,
account_number=resource_account,
assume_role=config.get("policies.role_name"),
region=resource_region or config.region,
session_name=sanitize_session_name("apply-resource-policy-" + user),
arn_partition="aws",
sts_client_kwargs=dict(
region_name=config.region,
endpoint_url=config.get(
"aws.sts_endpoint_url", "https://sts.{region}.amazonaws.com"
).format(region=config.region),
),
client_kwargs=config.get("boto3.client_kwargs", {}),
retry_max_attempts=2,
)
if resource_type == "s3":
await sync_to_async(client.put_bucket_policy)(
Bucket=resource_name,
Policy=json.dumps(
change.policy.policy_document, escape_forward_slashes=False
),
)
elif resource_type == "sns":
await sync_to_async(client.set_topic_attributes)(
TopicArn=change.arn,
AttributeName="Policy",
AttributeValue=json.dumps(
change.policy.policy_document, escape_forward_slashes=False
),
)
elif resource_type == "sqs":
queue_url: dict = await sync_to_async(client.get_queue_url)(
QueueName=resource_name
)
await sync_to_async(client.set_queue_attributes)(
QueueUrl=queue_url.get("QueueUrl"),
Attributes={
"Policy": json.dumps(
change.policy.policy_document, escape_forward_slashes=False
)
},
)
elif resource_type == "iam":
role_name = resource_arn_parsed["resource_path"].split("/")[-1]
await sync_to_async(client.update_assume_role_policy)(
RoleName=role_name,
PolicyDocument=json.dumps(
change.policy.policy_document, escape_forward_slashes=False
),
)
# force refresh the role for which we just changed the assume role policy doc
await aws.fetch_iam_role(resource_account, change.arn, force_refresh=True)
response.action_results.append(
ActionResult(
status="success",
message=f"Successfully updated resource policy for {change.arn}",
)
)
change.status = Status.applied
except Exception as e:
log_data["message"] = "Exception occurred updating resource policy"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=f"Error occurred updating resource policy for {change.arn}"
+ str(e),
)
)
log_data["message"] = "Finished applying resource policy change"
log_data["response"] = response.dict()
log_data["request"] = extended_request.dict()
log_data["change"] = change.dict()
log.debug(log_data)
return response
async def _update_dynamo_with_change(
user: str,
extended_request: ExtendedRequestModel,
log_data: Dict,
response: PolicyRequestModificationResponseModel,
success_message: str,
error_message: str,
visible: bool = True,
):
dynamo = UserDynamoHandler(user)
try:
await dynamo.write_policy_request_v2(extended_request)
response.action_results.append(
ActionResult(status="success", message=success_message, visible=visible)
)
except Exception as e:
log_data["message"] = error_message
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
sentry_sdk.capture_exception()
response.errors += 1
response.action_results.append(
ActionResult(status="error", message=error_message + ": " + str(e))
)
return response
async def _get_specific_change(changes: ChangeModelArray, change_id: str):
for change in changes.changes:
if change.id == change_id:
return change
return None
async def maybe_approve_reject_request(
extended_request: ExtendedRequestModel,
user: str,
log_data: Dict,
response: PolicyRequestModificationResponseModel,
) -> PolicyRequestModificationResponseModel:
any_changes_applied = False
any_changes_pending = False
any_changes_cancelled = False
request_status_changed = False
for change in extended_request.changes.changes:
if change.status == Status.applied:
any_changes_applied = True
if change.status == Status.not_applied:
# Don't consider "unsupported" resource policies as "pending", since they can't be applied.
if (
change.change_type == "resource_policy"
or change.change_type == "sts_resource_policy"
) and change.supported is False:
continue
# Requests should still be marked as approved if they have pending autogenerated changes
if change.autogenerated:
continue
any_changes_pending = True
if change.status == Status.cancelled:
any_changes_cancelled = True
# Automatically mark request as "approved" if at least one of the changes in the request is approved, and
# nothing else is pending
if any_changes_applied and not any_changes_pending:
extended_request.request_status = RequestStatus.approved
request_status_changed = True
# Automatically mark request as "cancelled" if all changes in the request are cancelled
if not any_changes_applied and not any_changes_pending and any_changes_cancelled:
extended_request.request_status = RequestStatus.cancelled
request_status_changed = True
if request_status_changed:
extended_request.reviewer = user
response = await _update_dynamo_with_change(
user,
extended_request,
log_data,
response,
"Successfully updated request status",
"Error updating request in dynamo",
visible=False,
)
await send_communications_policy_change_request_v2(extended_request)
account_id = await get_resource_account(
extended_request.principal.principal_arn
)
if extended_request.principal.principal_arn.startswith("aws:aws:iam::"):
await aws.fetch_iam_role(
account_id, extended_request.principal.principal_arn, force_refresh=True
)
return response
class NoMatchingRequest(BaseException):
"""Cannot find a matching request"""
def __init__(self, msg=""):
stats.count("NoMatchingRequest")
super().__init__(msg)
class Unauthorized(BaseException):
"""Unauthorized"""
def __init__(self, msg=""):
stats.count("Unauthorized")
super().__init__(msg)
class InvalidRequestParameter(BaseException):
"""Invalid Request Parameter passed to function"""
def __init__(self, msg=""):
stats.count("InvalidRequestParameter")
super().__init__(msg)
def can_admin_policies(user: str, user_groups: List[str]) -> bool:
if can_admin_all(user, user_groups):
return True
if is_in_group(
user,
user_groups,
[
*config.get("groups.can_admin_policies", []),
*config.get("dynamic_config.groups.can_admin_policies", []),
],
):
return True
return False
async def get_resource_account(arn: str) -> str:
"""Return the AWS account ID that owns a resource.
In most cases, this will pull the ID directly from the ARN.
If we are unsuccessful in pulling the account from ARN, we try to grab it from our resources cache
"""
red = await RedisHandler().redis()
resource_account: str = get_account_from_arn(arn)
if resource_account:
return resource_account
resources_from_aws_config_redis_key: str = config.get(
"aws_config_cache.redis_key", "AWSCONFIG_RESOURCE_CACHE"
)
if not red.exists(resources_from_aws_config_redis_key):
# This will force a refresh of our redis cache if the data exists in S3
await retrieve_json_data_from_redis_or_s3(
redis_key=resources_from_aws_config_redis_key,
s3_bucket=config.get("aws_config_cache_combined.s3.bucket"),
s3_key=config.get(
"aws_config_cache_combined.s3.file",
"aws_config_cache_combined/aws_config_resource_cache_combined_v1.json.gz",
),
redis_data_type="hash",
)
resource_info = await redis_hget(resources_from_aws_config_redis_key, arn)
if resource_info:
return json.loads(resource_info).get("accountId", "")
elif "arn:aws:s3:::" in arn:
# Try to retrieve S3 bucket information from S3 cache. This is inefficient and we should ideally have
# retrieved this info from our AWS Config cache, but we've encountered problems with AWS Config historically
# that have necessitated this code.
s3_cache = await retrieve_json_data_from_redis_or_s3(
redis_key=config.get("redis.s3_buckets_key", "S3_BUCKETS"),
redis_data_type="hash",
)
search_bucket_name = arn.split(":")[-1]
for bucket_account_id, buckets in s3_cache.items():
buckets_j = json.loads(buckets)
if search_bucket_name in buckets_j:
return bucket_account_id
return ""
async def can_move_back_to_pending_v2(
extended_request: ExtendedRequestModel, last_updated, current_user, groups
):
if extended_request.request_status in [
RequestStatus.cancelled,
RequestStatus.rejected,
]:
# Don't allow returning requests to pending state if more than a day has passed since the last update
if last_updated < int(time.time()) - 86400:
return False
# Allow admins to return requests back to pending state
if can_admin_policies(current_user, groups):
return True
return False
async def can_update_cancel_requests_v2(requester_username, user, groups):
# Users can update their own requests
can_update = user == requester_username
# Allow admins to update / cancel requests
if not can_update:
if can_admin_policies(user, groups):
return True
return can_update
async def send_communications_policy_change_request_v2(
extended_request: ExtendedRequestModel,
):
"""
Send an email for a status change for a policy request
:param extended_request: ExtendedRequestModel
:return:
"""
request_uri = await get_policy_request_uri_v2(extended_request)
await send_policy_request_status_update_v2(extended_request, request_uri)
async def send_communications_new_comment(
extended_request: ExtendedRequestModel, user: str, to_addresses=None
):
"""
Send an email for a new comment.
Note: until ABAC work is completed, if to_addresses is empty, we will send an email to
fallback reviewers
:param extended_request: ExtendedRequestModel
:param user: user making the comment
:param to_addresses: List of addresses to send the email to
:return:
"""
if not to_addresses:
to_addresses = config.get("groups.fallback_policy_request_reviewers", [])
request_uri = await get_policy_request_uri_v2(extended_request)
await send_new_comment_notification(
extended_request, to_addresses, user, request_uri
)
class ActionResult(BaseModel):
status: Optional[str] = None
message: Optional[str] = None
class RequestStatus(Enum):
pending = "pending"
cancelled = "cancelled"
approved = "approved"
rejected = "rejected"
class Status(Enum):
applied = "applied"
not_applied = "not_applied"
cancelled = "cancelled"
class UserModel(BaseModel):
email: Optional[str] = None
extended_info: Optional[Dict[str, Any]] = None
details_url: Optional[str] = Field(None, example="https://details_about/user")
photo_url: Optional[str] = Field(
None, example="https://user_photos/user_thumbnail.jpg"
)
class Command(Enum):
add_comment = "add_comment"
approve_request = "approve_request"
reject_request = "reject_request"
cancel_request = "cancel_request"
apply_change = "apply_change"
update_change = "update_change"
cancel_change = "cancel_change"
move_back_to_pending = "move_back_to_pending"
class CommentRequestModificationModel(RequestModificationBaseModel):
comment_text: str
class UpdateChangeModificationModel(RequestModificationBaseModel):
policy_document: Dict[str, Any]
change_id: str
class ApplyChangeModificationModel(RequestModificationBaseModel):
policy_document: Optional[Dict[str, Any]] = None
change_id: str
class CancelChangeModificationModel(RequestModificationBaseModel):
policy_document: Optional[Dict[str, Any]] = None
change_id: str
class PolicyRequestModificationRequestModel(BaseModel):
modification_model: Union[
CommentRequestModificationModel,
UpdateChangeModificationModel,
ApplyChangeModificationModel,
ApproveRequestModificationModel,
MoveToPendingRequestModificationModel,
ChangeRequestStatusModificationModel,
]
class PolicyRequestModificationResponseModel(BaseModel):
errors: Optional[int] = None
action_results: Optional[List[ActionResult1]] = None
class CommentModel(BaseModel):
id: str
timestamp: datetime
edited: Optional[bool] = None
last_modified: Optional[datetime] = None
user_email: str
user: Optional[UserModel] = None
text: str
class ExtendedRequestModel(RequestModel):
changes: ChangeModelArray
requester_info: UserModel
reviewer: Optional[str] = None
comments: Optional[List[CommentModel]] = None
The provided code snippet includes necessary dependencies for implementing the `parse_and_apply_policy_request_modification` function. Write a Python function `async def parse_and_apply_policy_request_modification( extended_request: ExtendedRequestModel, policy_request_model: PolicyRequestModificationRequestModel, user: str, user_groups, last_updated, approval_probe_approved=False, ) -> PolicyRequestModificationResponseModel` to solve the following problem:
Parses the policy request modification changes :param extended_request: ExtendedRequestModel :param user: Str - requester's email address :param policy_request_model: PolicyRequestModificationRequestModel :param user_groups: user's groups :param last_updated: :param approval_probe_approved: Whether this change was approved by an auto-approval probe. If not, user needs to be authorized to make the change. :return PolicyRequestModificationResponseModel
Here is the function:
async def parse_and_apply_policy_request_modification(
extended_request: ExtendedRequestModel,
policy_request_model: PolicyRequestModificationRequestModel,
user: str,
user_groups,
last_updated,
approval_probe_approved=False,
) -> PolicyRequestModificationResponseModel:
"""
Parses the policy request modification changes
:param extended_request: ExtendedRequestModel
:param user: Str - requester's email address
:param policy_request_model: PolicyRequestModificationRequestModel
:param user_groups: user's groups
:param last_updated:
:param approval_probe_approved: Whether this change was approved by an auto-approval probe. If not, user needs to be
authorized to make the change.
:return PolicyRequestModificationResponseModel
"""
log_data: Dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"request": extended_request.dict(),
"request_changes": policy_request_model.dict(),
"message": "Parsing request modification changes",
}
log.debug(log_data)
response = PolicyRequestModificationResponseModel(errors=0, action_results=[])
request_changes = policy_request_model.modification_model
if request_changes.command in [Command.update_change, Command.cancel_request]:
can_update_cancel = await can_update_cancel_requests_v2(
extended_request.requester_email, user, user_groups
)
if not can_update_cancel:
raise Unauthorized(
"You are not authorized to update or cancel changes in this request"
)
if request_changes.command in [
Command.apply_change,
Command.approve_request,
Command.reject_request,
]:
can_manage_policy_request = can_admin_policies(user, user_groups)
# Authorization required if the policy wasn't approved by an auto-approval probe.
should_apply_because_auto_approved = (
request_changes.command == Command.apply_change and approval_probe_approved
)
if not can_manage_policy_request and not should_apply_because_auto_approved:
raise Unauthorized("You are not authorized to manage this request")
if request_changes.command == Command.move_back_to_pending:
can_move_back_to_pending = await can_move_back_to_pending_v2(
extended_request, last_updated, user, user_groups
)
if not can_move_back_to_pending:
raise Unauthorized("Cannot move this request back to pending")
# If here, then the person is authorized to make the change they want
# For cancelled / rejected requests, only moving back to pending, adding comments is permitted
if extended_request.request_status in [
RequestStatus.cancelled,
RequestStatus.rejected,
] and request_changes.command not in [
Command.add_comment,
Command.move_back_to_pending,
]:
raise InvalidRequestParameter(
f"Cannot perform {request_changes.command.value} on "
f"{extended_request.request_status.value} requests"
)
if request_changes.command == Command.add_comment:
# TODO: max comment size? prevent spamming?
comment_model = CommentRequestModificationModel.parse_obj(request_changes)
user_comment = CommentModel(
id=str(uuid.uuid4()),
timestamp=int(time.time()),
user_email=user,
user=UserModel(
email=user,
extended_info=await auth.get_user_info(user),
details_url=config.config_plugin().get_employee_info_url(user),
photo_url=config.config_plugin().get_employee_photo_url(user),
),
last_modified=int(time.time()),
text=comment_model.comment_text,
)
extended_request.comments.append(user_comment)
success_message = "Successfully added comment"
error_message = "Error occurred adding comment"
response = await _update_dynamo_with_change(
user, extended_request, log_data, response, success_message, error_message
)
if user == extended_request.requester_email:
# User who created the request adding a comment, notification should go to reviewers
await send_communications_new_comment(extended_request, user)
else:
# A reviewer or someone else making the comment, notification should go to original requester
await send_communications_new_comment(
extended_request, user, to_addresses=[extended_request.requester_email]
)
elif request_changes.command == Command.update_change:
update_change_model = UpdateChangeModificationModel.parse_obj(request_changes)
specific_change = await _get_specific_change(
extended_request.changes, update_change_model.change_id
)
# We only support updating inline policies, assume role policy documents and resource policies that haven't
# applied already
if (
specific_change
and specific_change.change_type
in [
"inline_policy",
"resource_policy",
"sts_resource_policy",
"assume_role_policy",
"managed_policy_resource",
]
and specific_change.status == Status.not_applied
):
specific_change.policy.policy_document = update_change_model.policy_document
if (
specific_change.change_type == "resource_policy"
or specific_change.change_type == "sts_resource_policy"
):
# Special case, if it's autogenerated and a user modifies it, update status to
# not autogenerated, so we don't overwrite it on page refresh
specific_change.autogenerated = False
success_message = "Successfully updated policy document"
error_message = "Error occurred updating policy document"
specific_change.updated_by = user
response = await _update_dynamo_with_change(
user,
extended_request,
log_data,
response,
success_message,
error_message,
)
else:
raise NoMatchingRequest(
"Unable to find a compatible non-applied change with "
"that ID in this policy request"
)
elif request_changes.command == Command.apply_change:
apply_change_model = ApplyChangeModificationModel.parse_obj(request_changes)
specific_change = await _get_specific_change(
extended_request.changes, apply_change_model.change_id
)
if specific_change and specific_change.status == Status.not_applied:
# Update the policy doc locally for supported changes, if it needs to be updated
if apply_change_model.policy_document and specific_change.change_type in [
"inline_policy",
"resource_policy",
"sts_resource_policy",
"assume_role_policy",
"managed_policy_resource",
]:
specific_change.policy.policy_document = (
apply_change_model.policy_document
)
managed_policy_arn_regex = re.compile(r"^arn:aws:iam::\d{12}:policy/.+")
if (
specific_change.change_type == "resource_policy"
or specific_change.change_type == "sts_resource_policy"
):
response = await apply_resource_policy_change(
extended_request, specific_change, response, user
)
elif (
specific_change.change_type == "resource_tag"
and not specific_change.principal.principal_arn.startswith(
"arn:aws:iam::"
)
):
response = await apply_non_iam_resource_tag_change(
extended_request, specific_change, response, user
)
elif (
specific_change.change_type == "resource_tag"
and managed_policy_arn_regex.search(
specific_change.principal.principal_arn
)
):
response = await apply_managed_policy_resource_tag_change(
extended_request, specific_change, response, user
)
elif specific_change.change_type == "managed_policy_resource":
response = await apply_managed_policy_resource_change(
extended_request, specific_change, response, user
)
else:
# Save current policy by populating "old" policies at the time of application for historical record
extended_request = await populate_old_policies(extended_request, user)
await apply_changes_to_role(
extended_request, response, user, specific_change.id
)
account_id = await get_resource_account(
extended_request.principal.principal_arn
)
await aws.fetch_iam_role(
account_id,
extended_request.principal.principal_arn,
force_refresh=True,
)
if specific_change.status == Status.applied:
# Change was successful, update in dynamo
success_message = "Successfully updated change in dynamo"
error_message = "Error updating change in dynamo"
specific_change.updated_by = user
response = await _update_dynamo_with_change(
user,
extended_request,
log_data,
response,
success_message,
error_message,
visible=False,
)
else:
raise NoMatchingRequest(
"Unable to find a compatible non-applied change with "
"that ID in this policy request"
)
elif request_changes.command == Command.cancel_change:
cancel_change_model = CancelChangeModificationModel.parse_obj(request_changes)
specific_change = await _get_specific_change(
extended_request.changes, cancel_change_model.change_id
)
if specific_change and specific_change.status == Status.not_applied:
# Update the status
specific_change.status = Status.cancelled
specific_change.updated_by = user
# Update in dynamo
success_message = "Successfully updated change in dynamo"
error_message = "Error updating change in dynamo"
response = await _update_dynamo_with_change(
user,
extended_request,
log_data,
response,
success_message,
error_message,
visible=False,
)
else:
raise NoMatchingRequest(
"Unable to find a compatible non-applied change with "
"that ID in this policy request"
)
elif request_changes.command == Command.cancel_request:
if extended_request.request_status != RequestStatus.pending:
raise InvalidRequestParameter(
"Request cannot be cancelled as it's status "
f"is {extended_request.request_status.value}"
)
for change in extended_request.changes.changes:
if change.status == Status.applied:
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=(
"Request cannot be cancelled because at least one change has been applied already. "
"Please apply or cancel the other changes."
),
)
)
response = await maybe_approve_reject_request(
extended_request, user, log_data, response
)
return response
extended_request.request_status = RequestStatus.cancelled
success_message = "Successfully cancelled request"
error_message = "Error cancelling request"
extended_request.reviewer = user
response = await _update_dynamo_with_change(
user, extended_request, log_data, response, success_message, error_message
)
await send_communications_policy_change_request_v2(extended_request)
elif request_changes.command == Command.reject_request:
if extended_request.request_status != RequestStatus.pending:
raise InvalidRequestParameter(
f"Request cannot be rejected "
f"as it's status is {extended_request.request_status.value}"
)
for change in extended_request.changes.changes:
if change.status == Status.applied:
response.errors += 1
response.action_results.append(
ActionResult(
status="error",
message=(
"Request cannot be rejected because at least one change has been applied already. "
"Please apply or cancel the other changes."
),
)
)
response = await maybe_approve_reject_request(
extended_request, user, log_data, response
)
return response
extended_request.request_status = RequestStatus.rejected
success_message = "Successfully rejected request"
error_message = "Error rejected request"
extended_request.reviewer = user
response = await _update_dynamo_with_change(
user, extended_request, log_data, response, success_message, error_message
)
await send_communications_policy_change_request_v2(extended_request)
elif request_changes.command == Command.move_back_to_pending:
extended_request.request_status = RequestStatus.pending
success_message = "Successfully moved request back to pending"
error_message = "Error moving request back to pending"
response = await _update_dynamo_with_change(
user, extended_request, log_data, response, success_message, error_message
)
# This marks a request as complete. This essentially means that all necessary actions have been taken with the
# request, and doesn't apply any changes.
elif request_changes.command == Command.approve_request:
if extended_request.request_status != RequestStatus.pending:
raise InvalidRequestParameter(
"Request cannot be approved as it's "
f"status is {extended_request.request_status.value}"
)
# Save current policy by populating "old" policies at the time of application for historical record
extended_request = await populate_old_policies(extended_request, user)
extended_request.request_status = RequestStatus.approved
extended_request.reviewer = user
success_message = "Successfully updated request status"
error_message = "Error updating request in dynamo"
response = await _update_dynamo_with_change(
user,
extended_request,
log_data,
response,
success_message,
error_message,
visible=False,
)
await send_communications_policy_change_request_v2(extended_request)
account_id = await get_resource_account(
extended_request.principal.principal_arn
)
await aws.fetch_iam_role(
account_id, extended_request.principal.principal_arn, force_refresh=True
)
response = await maybe_approve_reject_request(
extended_request, user, log_data, response
)
log_data["message"] = "Done parsing/applying request modification changes"
log_data["request"] = extended_request.dict()
log_data["response"] = response.dict()
log_data["error"] = None
log.debug(log_data)
return response | Parses the policy request modification changes :param extended_request: ExtendedRequestModel :param user: Str - requester's email address :param policy_request_model: PolicyRequestModificationRequestModel :param user_groups: user's groups :param last_updated: :param approval_probe_approved: Whether this change was approved by an auto-approval probe. If not, user needs to be authorized to make the change. :return PolicyRequestModificationResponseModel |
162,089 | import sys
from typing import List
import boto3
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.generic import generate_html, get_principal_friendly_name
from consoleme.lib.groups import get_group_url
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.models import ExtendedRequestModel, RequestStatus
async def send_email(
to_addresses: List[str],
subject: str,
body: str,
sending_app: str = "consoleme",
region: str = config.get("ses.region", "us-west-2"),
charset: str = "UTF-8",
) -> None:
client = boto3.client(
"ses", region_name=region, **config.get("boto3.client_kwargs", {})
)
sender = config.get(f"ses.{sending_app}.sender")
log_data = {
"to_user": to_addresses,
"region": region,
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"sender": sender,
"subject": subject,
}
if not config.get("ses.arn"):
log.error(
{
**log_data,
"error": "Configuration value for `ses.arn` is not defined. Unable to send e-mail.",
}
)
return
if not sender:
log.error(
{
**log_data,
"error": f"Configuration value for `ses.{sending_app}.sender` is not defined. Unable to send e-mail.",
}
)
return
if config.get("development") and config.get("ses.override_receivers_for_dev"):
log_data["original_to_addresses"] = to_addresses
log_data["message"] = "Overriding to_address"
to_addresses = config.get("ses.override_receivers_for_dev")
log_data["new_to_addresses"] = to_addresses
log.debug(log_data)
# Handle non-list recipients
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
try:
response = await sync_to_async(client.send_email)(
Destination={"ToAddresses": to_addresses}, # This should be a list
Message={
"Body": {
"Html": {"Charset": charset, "Data": body},
"Text": {"Charset": charset, "Data": body},
},
"Subject": {"Charset": charset, "Data": subject},
},
Source=sender,
SourceArn=config.get("ses.arn"),
)
# Display an error if something goes wrong.
except Exception:
stats.count("lib.ses.error")
log_data["message"] = "Exception sending email"
log.error(log_data, exc_info=True)
else:
stats.count("lib.ses.success")
log_data["message"] = "Email sent successfully"
log_data["response"] = response["MessageId"]
log.debug(log_data)
async def send_access_email_to_user(
user: str,
group: str,
updated_by: str,
status: str,
request_url: str,
group_url: str,
reviewer_comments: None = None,
sending_app: str = "consoleme",
) -> None:
app_name = config.get(f"ses.{sending_app}.name", sending_app)
subject = f"{app_name}: Request for group {group} has been {status}"
to_addresses = [user, updated_by]
group_link = f"<a href={group_url}>{group}</a>"
message = f"Your request for group {group_link} has been {status} by {updated_by}."
if status == "approved":
message += " Please allow up to 30 minutes for your group to propagate. "
reviewer_comments_section = ""
if reviewer_comments:
reviewer_comments_section = f"Reviewer Comments: {reviewer_comments}"
body = f"""<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Request Status</title>
</head>
<body>
{message} <br>
{reviewer_comments_section} <br>
See your request here: {request_url}.<br>
<br>
{config.get('ses.support_reference', '')}
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</body>
</html>"""
await send_email(to_addresses, subject, body, sending_app=sending_app) | null |
162,090 | import sys
from typing import List
import boto3
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.generic import generate_html, get_principal_friendly_name
from consoleme.lib.groups import get_group_url
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.models import ExtendedRequestModel, RequestStatus
async def send_email(
to_addresses: List[str],
subject: str,
body: str,
sending_app: str = "consoleme",
region: str = config.get("ses.region", "us-west-2"),
charset: str = "UTF-8",
) -> None:
client = boto3.client(
"ses", region_name=region, **config.get("boto3.client_kwargs", {})
)
sender = config.get(f"ses.{sending_app}.sender")
log_data = {
"to_user": to_addresses,
"region": region,
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"sender": sender,
"subject": subject,
}
if not config.get("ses.arn"):
log.error(
{
**log_data,
"error": "Configuration value for `ses.arn` is not defined. Unable to send e-mail.",
}
)
return
if not sender:
log.error(
{
**log_data,
"error": f"Configuration value for `ses.{sending_app}.sender` is not defined. Unable to send e-mail.",
}
)
return
if config.get("development") and config.get("ses.override_receivers_for_dev"):
log_data["original_to_addresses"] = to_addresses
log_data["message"] = "Overriding to_address"
to_addresses = config.get("ses.override_receivers_for_dev")
log_data["new_to_addresses"] = to_addresses
log.debug(log_data)
# Handle non-list recipients
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
try:
response = await sync_to_async(client.send_email)(
Destination={"ToAddresses": to_addresses}, # This should be a list
Message={
"Body": {
"Html": {"Charset": charset, "Data": body},
"Text": {"Charset": charset, "Data": body},
},
"Subject": {"Charset": charset, "Data": subject},
},
Source=sender,
SourceArn=config.get("ses.arn"),
)
# Display an error if something goes wrong.
except Exception:
stats.count("lib.ses.error")
log_data["message"] = "Exception sending email"
log.error(log_data, exc_info=True)
else:
stats.count("lib.ses.success")
log_data["message"] = "Email sent successfully"
log_data["response"] = response["MessageId"]
log.debug(log_data)
async def send_request_created_to_user(
user, group, updated_by, status, request_url, sending_app="consoleme"
):
app_name = config.get(f"ses.{sending_app}.name", sending_app)
subject = f"{app_name}: Request for group {group} has been created"
to_addresses = [user, updated_by]
message = f"Your request for group {group} has been created."
if status == "approved":
message += " Please allow up to 30 minutes for your group to propagate. "
body = f"""<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Request Status</title>
</head>
<body>
{message} <br>
<br>
See your request here: {request_url}.<br>
<br>
{config.get('ses.support_reference', '')}
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</body>
</html>"""
await send_email(to_addresses, subject, body, sending_app=sending_app) | null |
162,091 | import sys
from typing import List
import boto3
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.generic import generate_html, get_principal_friendly_name
from consoleme.lib.groups import get_group_url
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.models import ExtendedRequestModel, RequestStatus
async def send_email(
to_addresses: List[str],
subject: str,
body: str,
sending_app: str = "consoleme",
region: str = config.get("ses.region", "us-west-2"),
charset: str = "UTF-8",
) -> None:
client = boto3.client(
"ses", region_name=region, **config.get("boto3.client_kwargs", {})
)
sender = config.get(f"ses.{sending_app}.sender")
log_data = {
"to_user": to_addresses,
"region": region,
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"sender": sender,
"subject": subject,
}
if not config.get("ses.arn"):
log.error(
{
**log_data,
"error": "Configuration value for `ses.arn` is not defined. Unable to send e-mail.",
}
)
return
if not sender:
log.error(
{
**log_data,
"error": f"Configuration value for `ses.{sending_app}.sender` is not defined. Unable to send e-mail.",
}
)
return
if config.get("development") and config.get("ses.override_receivers_for_dev"):
log_data["original_to_addresses"] = to_addresses
log_data["message"] = "Overriding to_address"
to_addresses = config.get("ses.override_receivers_for_dev")
log_data["new_to_addresses"] = to_addresses
log.debug(log_data)
# Handle non-list recipients
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
try:
response = await sync_to_async(client.send_email)(
Destination={"ToAddresses": to_addresses}, # This should be a list
Message={
"Body": {
"Html": {"Charset": charset, "Data": body},
"Text": {"Charset": charset, "Data": body},
},
"Subject": {"Charset": charset, "Data": subject},
},
Source=sender,
SourceArn=config.get("ses.arn"),
)
# Display an error if something goes wrong.
except Exception:
stats.count("lib.ses.error")
log_data["message"] = "Exception sending email"
log.error(log_data, exc_info=True)
else:
stats.count("lib.ses.success")
log_data["message"] = "Email sent successfully"
log_data["response"] = response["MessageId"]
log.debug(log_data)
async def send_request_to_secondary_approvers(
secondary_approvers,
group,
request_url,
pending_requests_url,
sending_app="consoleme",
):
app_name = config.get(f"ses.{sending_app}.name", sending_app)
subject = f"{app_name}: A request for group {group} requires your approval"
to_addresses = secondary_approvers
message = f"A request for group {group} requires your approval."
body = f"""<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Request Status</title>
</head>
<body>
{message} <br>
<br>
See the request here: {request_url}.<br>
<br>
You can find all pending requests waiting your approval here: {pending_requests_url}. <br>
<br>
{config.get('ses.support_reference', '')}
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</body>
</html>"""
await send_email(to_addresses, subject, body, sending_app=sending_app) | null |
162,092 | import sys
from typing import List
import boto3
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.generic import generate_html, get_principal_friendly_name
from consoleme.lib.groups import get_group_url
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.models import ExtendedRequestModel, RequestStatus
async def send_email(
to_addresses: List[str],
subject: str,
body: str,
sending_app: str = "consoleme",
region: str = config.get("ses.region", "us-west-2"),
charset: str = "UTF-8",
) -> None:
client = boto3.client(
"ses", region_name=region, **config.get("boto3.client_kwargs", {})
)
sender = config.get(f"ses.{sending_app}.sender")
log_data = {
"to_user": to_addresses,
"region": region,
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"sender": sender,
"subject": subject,
}
if not config.get("ses.arn"):
log.error(
{
**log_data,
"error": "Configuration value for `ses.arn` is not defined. Unable to send e-mail.",
}
)
return
if not sender:
log.error(
{
**log_data,
"error": f"Configuration value for `ses.{sending_app}.sender` is not defined. Unable to send e-mail.",
}
)
return
if config.get("development") and config.get("ses.override_receivers_for_dev"):
log_data["original_to_addresses"] = to_addresses
log_data["message"] = "Overriding to_address"
to_addresses = config.get("ses.override_receivers_for_dev")
log_data["new_to_addresses"] = to_addresses
log.debug(log_data)
# Handle non-list recipients
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
try:
response = await sync_to_async(client.send_email)(
Destination={"ToAddresses": to_addresses}, # This should be a list
Message={
"Body": {
"Html": {"Charset": charset, "Data": body},
"Text": {"Charset": charset, "Data": body},
},
"Subject": {"Charset": charset, "Data": subject},
},
Source=sender,
SourceArn=config.get("ses.arn"),
)
# Display an error if something goes wrong.
except Exception:
stats.count("lib.ses.error")
log_data["message"] = "Exception sending email"
log.error(log_data, exc_info=True)
else:
stats.count("lib.ses.success")
log_data["message"] = "Email sent successfully"
log_data["response"] = response["MessageId"]
log.debug(log_data)
def generate_html(d: List[Dict[str, Union[str, bool]]]) -> str:
"""
Pass in a dict with a list of rows to include in a formatted table. This will return the HTML for the table.
:param d:
:return:
html: HTML formatted table
"""
if not d:
return
pd.set_option("display.max_colwidth", -1)
df = pd.DataFrame(d)
html = df.to_html(classes=["ui", "celled", "table"], escape=False, index=False)
return html
def get_group_url(group: str) -> str:
return "{}/accessui/group/{}".format(config.get("url"), group)
The provided code snippet includes necessary dependencies for implementing the `send_group_modification_notification` function. Write a Python function `async def send_group_modification_notification( groups, to_address, sending_app="consoleme" )` to solve the following problem:
Send an email containing group changes to a notification address Example of `groups` dict: { "awesome_group_1@netflix.com": [ {"name": "tswift@netflix.com", "type": "USER"}, {"name": "agrande@netflix.com", "type": "USER"}, ], "awesome_group_2@netflix.com": [ {"name": "lizzo@netflix.com", "type": "USER"}, {"name": "beilish@netflix.com", "type": "USER"}, ], } :param groups: map of groups and added members :type groups: dict :param to_address: recipient of notification email :type to_address: str :param sending_app: name of application :type sending_app: str
Here is the function:
async def send_group_modification_notification(
groups, to_address, sending_app="consoleme"
):
"""
Send an email containing group changes to a notification address
Example of `groups` dict:
{
"awesome_group_1@netflix.com": [
{"name": "tswift@netflix.com", "type": "USER"},
{"name": "agrande@netflix.com", "type": "USER"},
],
"awesome_group_2@netflix.com": [
{"name": "lizzo@netflix.com", "type": "USER"},
{"name": "beilish@netflix.com", "type": "USER"},
],
}
:param groups: map of groups and added members
:type groups: dict
:param to_address: recipient of notification email
:type to_address: str
:param sending_app: name of application
:type sending_app: str
"""
app_name = config.get(f"ses.{sending_app}.name", sending_app)
subject = f"{app_name}: Groups modified"
message = f"""Groups modified in {app_name}.<br>
You or a group you belong to are configured to receive a notification when new members are added to this group.<br>
Admins may click the group link below to view and modify this configuration."""
added_members_snippet = ""
for group, added_members in groups.items():
group_url = get_group_url(group)
group_link = f"<a href={group_url}>{group}</a>"
if added_members:
added_members_snippet += f"""<b>Users added to {group_link}</a></b>: <br>
{generate_html(added_members)}<br>
"""
body = f"""<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
{message}<br>
<br>
{added_members_snippet}<br>
<br>
<br>
{config.get('ses.support_reference', '')}
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</body>
</html>"""
await send_email(to_address, subject, body, sending_app=sending_app) | Send an email containing group changes to a notification address Example of `groups` dict: { "awesome_group_1@netflix.com": [ {"name": "tswift@netflix.com", "type": "USER"}, {"name": "agrande@netflix.com", "type": "USER"}, ], "awesome_group_2@netflix.com": [ {"name": "lizzo@netflix.com", "type": "USER"}, {"name": "beilish@netflix.com", "type": "USER"}, ], } :param groups: map of groups and added members :type groups: dict :param to_address: recipient of notification email :type to_address: str :param sending_app: name of application :type sending_app: str |
162,093 | import sys
from typing import List
import boto3
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.generic import generate_html, get_principal_friendly_name
from consoleme.lib.groups import get_group_url
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.models import ExtendedRequestModel, RequestStatus
async def send_email(
to_addresses: List[str],
subject: str,
body: str,
sending_app: str = "consoleme",
region: str = config.get("ses.region", "us-west-2"),
charset: str = "UTF-8",
) -> None:
client = boto3.client(
"ses", region_name=region, **config.get("boto3.client_kwargs", {})
)
sender = config.get(f"ses.{sending_app}.sender")
log_data = {
"to_user": to_addresses,
"region": region,
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"sender": sender,
"subject": subject,
}
if not config.get("ses.arn"):
log.error(
{
**log_data,
"error": "Configuration value for `ses.arn` is not defined. Unable to send e-mail.",
}
)
return
if not sender:
log.error(
{
**log_data,
"error": f"Configuration value for `ses.{sending_app}.sender` is not defined. Unable to send e-mail.",
}
)
return
if config.get("development") and config.get("ses.override_receivers_for_dev"):
log_data["original_to_addresses"] = to_addresses
log_data["message"] = "Overriding to_address"
to_addresses = config.get("ses.override_receivers_for_dev")
log_data["new_to_addresses"] = to_addresses
log.debug(log_data)
# Handle non-list recipients
if not isinstance(to_addresses, list):
to_addresses = [to_addresses]
try:
response = await sync_to_async(client.send_email)(
Destination={"ToAddresses": to_addresses}, # This should be a list
Message={
"Body": {
"Html": {"Charset": charset, "Data": body},
"Text": {"Charset": charset, "Data": body},
},
"Subject": {"Charset": charset, "Data": subject},
},
Source=sender,
SourceArn=config.get("ses.arn"),
)
# Display an error if something goes wrong.
except Exception:
stats.count("lib.ses.error")
log_data["message"] = "Exception sending email"
log.error(log_data, exc_info=True)
else:
stats.count("lib.ses.success")
log_data["message"] = "Email sent successfully"
log_data["response"] = response["MessageId"]
log.debug(log_data)
def generate_html(d: List[Dict[str, Union[str, bool]]]) -> str:
"""
Pass in a dict with a list of rows to include in a formatted table. This will return the HTML for the table.
:param d:
:return:
html: HTML formatted table
"""
if not d:
return
pd.set_option("display.max_colwidth", -1)
df = pd.DataFrame(d)
html = df.to_html(classes=["ui", "celled", "table"], escape=False, index=False)
return html
async def send_new_aws_groups_notification(
to_addresses, new_aws_groups, sending_app="consoleme"
):
app_name = config.get(f"ses.{sending_app}.name", sending_app)
subject = f"{app_name}: New AWS groups detected"
message = """New AWS login groups were created.<br>
ConsoleMe is configured to send notifications when new AWS-related google groups are detected.
This is to detect any accidentally or maliciously created google groups.<br>"""
added_groups_snippet = ""
if new_aws_groups:
added_groups_snippet = f"""<b>New groups</b>: <br>
{generate_html({"New Groups": new_aws_groups})}<br>
"""
body = f"""<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
{message}<br>
<br>
{added_groups_snippet}<br>
<br>
<br>
{config.get('ses.support_reference', '')}
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</body>
</html>"""
await send_email(to_addresses, subject, body, sending_app=sending_app) | null |
162,094 | import sys
from typing import List
import boto3
from asgiref.sync import sync_to_async
from consoleme.config import config
from consoleme.lib.generic import generate_html, get_principal_friendly_name
from consoleme.lib.groups import get_group_url
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.models import ExtendedRequestModel, RequestStatus
async def send_email(
to_addresses: List[str],
subject: str,
body: str,
sending_app: str = "consoleme",
region: str = config.get("ses.region", "us-west-2"),
charset: str = "UTF-8",
) -> None:
async def send_policy_request_status_update(
request, policy_change_uri, sending_app="consoleme"
):
app_name = config.get(f"ses.{sending_app}.name", sending_app)
subject = f"{app_name}: Policy change request for {request['arn']} has been {request['status']}"
if request["status"] == "pending":
subject = (
f"{app_name}: Policy change request for {request['arn']} has been created"
)
to_addresses = [request.get("username")]
message = (
f"A policy change request for {request['arn']} has been {request['status']}"
)
if request["status"] == "pending":
message = f"A policy change request for {request['arn']} has been created."
if {request["status"]} == "approved":
message += " and committed"
subject += " and committed"
body = f"""<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Policy Change Request Status Change</title>
</head>
<body>
{message} <br>
<br>
See the request here: {policy_change_uri}.<br>
<br>
<br>
{config.get('ses.support_reference', '')}
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</body>
</html>"""
await send_email(to_addresses, subject, body, sending_app=sending_app) | null |
162,095 | import copy
import sys
import tornado.httputil
from asgiref.sync import sync_to_async
from furl import furl
from onelogin.saml2.errors import OneLogin_Saml2_Error
from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPMetadataParser
from consoleme.config import config
from consoleme.config.config import dict_merge
from consoleme.exceptions.exceptions import WebAuthNError
from consoleme.lib.generic import should_force_redirect
log = config.get_logger()
async def init_saml_auth(request):
saml_config = copy.deepcopy(
config.get("get_user_by_saml_settings.saml_settings", {})
)
idp_metadata_url = config.get("get_user_by_saml_settings.idp_metadata_url")
if idp_metadata_url:
idp_metadata = OneLogin_Saml2_IdPMetadataParser.parse_remote(idp_metadata_url)
saml_config = dict_merge(saml_config, idp_metadata)
auth = await sync_to_async(OneLogin_Saml2_Auth)(
request,
saml_config,
custom_base_path=config.get("get_user_by_saml_settings.saml_path"),
)
return auth
async def prepare_tornado_request_for_saml(request):
dataDict = {}
for key in request.arguments:
dataDict[key] = request.arguments[key][0].decode("utf-8")
redirect_uri = dataDict.get("redirect_url")
redirect_path = request.path
redirect_port = tornado.httputil.split_host_and_port(request.host)[1]
if redirect_uri:
parsed_redirect_uri = furl(redirect_uri)
redirect_path = parsed_redirect_uri.pathstr
redirect_port = parsed_redirect_uri.port
result = {
"https": "on" if request == "https" else "off",
"http_host": tornado.httputil.split_host_and_port(request.host)[0],
"script_name": redirect_path,
"server_port": redirect_port,
"get_data": dataDict,
"post_data": dataDict,
"query_string": request.query,
}
return result
class WebAuthNError(tornado.web.HTTPError):
"""Authentication Error"""
def __init__(self, **kwargs):
kwargs["status_code"] = 401
super().__init__(**kwargs)
async def should_force_redirect(req):
"""
ConsoleMe should only force a 302 redirect for non-XHR requests
"""
if req.headers.get("X-Requested-With", "") == "XMLHttpRequest":
return False
if req.headers.get("Accept") == "application/json":
return False
return True
async def authenticate_user_by_saml(request):
log_data = {"function": f"{__name__}.{sys._getframe().f_code.co_name}"}
saml_req = await prepare_tornado_request_for_saml(request.request)
saml_auth = await init_saml_auth(saml_req)
force_redirect = await should_force_redirect(request.request)
try:
await sync_to_async(saml_auth.process_response)()
except OneLogin_Saml2_Error as e:
log_data["error"] = e
log.error(log_data)
if force_redirect:
return request.redirect(saml_auth.login())
else:
request.set_status(403)
request.write(
{
"type": "redirect",
"redirect_url": saml_auth.login(),
"reason": "unauthenticated",
"message": "User is not authenticated. Redirect to authenticate",
}
)
request.finish()
return
saml_errors = await sync_to_async(saml_auth.get_errors)()
if saml_errors:
log_data["error"] = saml_errors
log.error(log_data)
raise WebAuthNError(reason=saml_errors)
# We redirect the user to the login page if they are still not authenticated by this point
not_auth_warn = not await sync_to_async(saml_auth.is_authenticated)()
if not_auth_warn:
if force_redirect:
return request.redirect(saml_auth.login())
else:
request.set_status(403)
request.write(
{
"type": "redirect",
"redirect_url": saml_auth.login(),
"reason": "unauthenticated",
"message": "User is not authenticated. Redirect to authenticate",
}
)
request.finish()
return | null |
162,096 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
def str2bool(v: Optional[Union[bool, str]]) -> bool:
if isinstance(v, bytes):
v = v.decode()
if not v:
return False
if type(v) is bool and v is True:
return True
return v.lower() in ["true", "True"] | null |
162,097 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
The provided code snippet includes necessary dependencies for implementing the `divide_chunks` function. Write a Python function `def divide_chunks(list_, n)` to solve the following problem:
Yields successive n=zied chunks from list l by looping until length l. `divide_chunks(["a","b","c","d","e"], 2)` yields: ['a', 'b', 'c'] ['d', 'e']
Here is the function:
def divide_chunks(list_, n):
"""
Yields successive n=zied chunks from list l by looping
until length l.
`divide_chunks(["a","b","c","d","e"], 2)` yields:
['a', 'b', 'c']
['d', 'e']
"""
for i in range(0, len(list_), n):
yield list_[i : i + n] | Yields successive n=zied chunks from list l by looping until length l. `divide_chunks(["a","b","c","d","e"], 2)` yields: ['a', 'b', 'c'] ['d', 'e'] |
162,098 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
def auto_split(s: str) -> List[str]:
results = []
for i in s.splitlines():
results.extend(i.split(","))
return results | null |
162,099 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
def is_valid_role_arn(arn: str) -> bool:
# This is valid enough as far as we are concerned.
if not arn.startswith("arn:aws:iam::"):
return False
return True | null |
162,100 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
def regex_filter(
filter: Dict[str, str], items: List[Dict[str, Union[str, None, bool]]]
) -> List[Dict[str, Union[str, None, bool]]]:
if filter.get("filter"):
results = []
if filter.get("type", "") == "date":
from_date = None
to_date = None
try:
if filter.get("from_date"):
from_date = parser.parse(filter.get("from_date"))
if filter.get("to_date"):
to_date = parser.parse(filter.get("to_date"))
if not from_date and not to_date:
return items
except: # noqa
# Unable to parse date. Return items.
return results
for item in items:
item_date = parser.parse(
item.get(filter.get("field"))
) # What if invalid date
if from_date and to_date and from_date <= item_date <= to_date:
results.append(item)
continue
if from_date and not to_date and item_date >= from_date:
results.append(item)
continue
if to_date and not from_date and item_date <= to_date:
results.append(item)
continue
return results
else:
regexp = re.compile(r"{}".format(filter.get("filter")), re.IGNORECASE)
for item in items:
try:
if regexp.search(item.get(filter.get("field"))):
results.append(item)
except re.error:
# Regex error. Return no results
pass
return results
else:
return items | null |
162,101 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
async def write_json_error(message, obj):
result = {"status": "error", "message": message}
obj.write(json.dumps(result))
obj.finish() | null |
162,102 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
async def sort_nested_dictionary_lists(d):
for k, v in d.items():
if isinstance(v, list):
for i in range(0, len(v)):
if isinstance(v[i], dict):
v[i] = await sort_nested_dictionary_lists(v[i])
d[k] = sorted(v)
if isinstance(v, dict):
d[k] = await sort_nested_dictionary_lists(v)
return d | null |
162,103 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
def is_in_time_range(t, time_range):
valid_days = time_range.get("days")
if t.weekday() not in valid_days:
return False
valid_start_time = t.replace(
hour=time_range.get("hour_start", 0),
minute=time_range.get("minute_start", 0),
second=0,
microsecond=0,
)
valid_end_time = t.replace(
hour=time_range.get("hour_end", 0),
minute=time_range.get("minute_end", 0),
second=0,
microsecond=0,
)
if t < valid_start_time or t > valid_end_time:
return False
return True | null |
162,104 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
async def get_random_security_logo():
if config.get("consoleme_logo.image"):
return config.get("consoleme_logo.image")
month = datetime.now().month
summer = month in [6, 7, 8]
dir = "sunglasses" if summer else "nosunglasses"
file = f"{randint(1, 3)}.png" # nosec
return f"/images/logos/{dir}/{file}" | null |
162,105 | import random
import re
import string
from datetime import datetime
from random import randint
from typing import Any, Dict, List, Optional, Union
from urllib.parse import unquote_plus
import pandas as pd
import ujson as json
from dateutil import parser
from consoleme.config import config
from consoleme.exceptions.exceptions import MissingRequestParameter
from consoleme.models import (
AwsResourcePrincipalModel,
HoneybeeAwsResourceTemplatePrincipalModel,
)
async def filter_table(filter_key, filter_value, data):
if not (filter_key and filter_value):
# Filter parameters are incorrect. Don't filter
return data
results = []
if isinstance(filter_value, str):
try:
regexp = re.compile(r"{}".format(str(filter_value).strip()), re.IGNORECASE)
except: # noqa
# Regex is incorrect. Don't filter
return data
for d in data:
try:
if regexp.search(str(d.get(filter_key))):
results.append(d)
except re.error:
# Regex error. Return no results
pass
return results
elif (
isinstance(filter_value, list)
and len(filter_value) == 2
and isinstance(filter_value[0], int)
and isinstance(filter_value[1], int)
):
# Handles epoch time filter. We expect a start_time and an end_time in
# a list of elements, and they should be integers
for d in data:
if filter_value[0] < int(d.get(filter_key)) < filter_value[1]:
results.append(d)
return results | null |
162,106 | import asyncio
import html
import sys
from typing import Any, Dict, List, Optional, Union
import googleapiclient.discovery
import ujson as json
from asgiref.sync import sync_to_async
from google.oauth2 import service_account
from googleapiclient.discovery import Resource
from googleapiclient.errors import HttpError
from retrying import retry
from validate_email import validate_email
from consoleme.config import config
from consoleme.exceptions.exceptions import (
BackgroundCheckNotPassedException,
BulkAddPrevented,
DifferentUserGroupDomainException,
MissingConfigurationValue,
NoCredentialSubjectException,
NoGroupsException,
NotAMemberException,
UnableToModifyRestrictedGroupMembers,
UnauthorizedToAccess,
UserAlreadyAMemberOfGroupException,
)
from consoleme.lib.auth import can_modify_members
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.groups import does_group_require_bg_check
from consoleme.lib.plugins import get_plugin_by_name
stats = get_plugin_by_name(config.get("plugins.metrics", "default_metrics"))()
log = config.get_logger()
auth = get_plugin_by_name(config.get("plugins.auth", "default_auth"))()
async def add_user_to_group(
user_email: str,
google_group_email: str,
updated_by: Optional[str] = None,
role: str = "MEMBER",
dry_run: None = None,
service: Optional[Resource] = None,
request: Optional[Dict[str, Union[int, str]]] = None,
) -> Dict[str, bool]:
"""Add user member to group."""
dynamo = UserDynamoHandler()
result = {"done": True}
function = f"{__name__}.{sys._getframe().f_code.co_name}"
stats.count(function)
log_data = {
"function": function,
"user_email": user_email,
"google_group_email": google_group_email,
"updated_by": updated_by,
"role": role,
"dry_run": dry_run,
"message": "Adding user to group",
}
if not service:
service = await get_service("admin", "directory_v1", google_group_email)
existing = await list_group_members(google_group_email, dry_run=dry_run)
if user_email in existing:
log_data["message"] = "Unable to add user to group. User is already a member."
log.warning(log_data)
result["done"] = False
result["message"] = log_data["message"]
raise UserAlreadyAMemberOfGroupException(result["message"])
group_info = await auth.get_group_info(google_group_email, members=False)
await raise_if_requires_bgcheck_and_no_bgcheck(user_email, group_info)
await raise_if_not_same_domain(user_email, group_info)
await raise_if_restricted(user_email, group_info)
await raise_if_bulk_add_disabled_and_no_request(group_info, request)
if not dry_run:
stats.count(
"google.add_user_to_group",
tags={
"user_email": user_email,
"google_group_email": google_group_email,
"updated_by": updated_by,
},
)
await insert_group_members_call(service, google_group_email, user_email, role)
await dynamo.create_group_log_entry(
google_group_email, user_email, updated_by, "Added"
)
log.info(log_data)
return result
import asyncio
def can_modify_members(
user: str, user_groups: List[str], group_info: Optional[Any]
) -> bool:
# No users can modify members on restricted groups
if group_info and group_info.restricted:
return False
if can_admin_all(user, user_groups):
return True
if is_in_group(
user,
user_groups,
[
*config.get("groups.can_admin_restricted", []),
*config.get("dynamic_config.groups.can_admin_restricted", []),
],
):
return True
if is_in_group(
user,
user_groups,
[
*config.get("groups.can_modify_members", []),
*config.get("dynamic_config.groups.can_modify_members", []),
],
):
return True
return False
async def add_user_to_group_task(
member: str,
group: str,
requesting_user: str,
requesting_users_groups: List[str],
semaphore=None,
service: None = None,
) -> Dict[str, Union[str, bool]]:
if not semaphore:
semaphore = asyncio.BoundedSemaphore(10)
async with semaphore:
stats.count(
"add_user_to_group_task.attempt",
tags={"member": member, "group": group, "requesting_user": requesting_user},
)
member = member.strip()
result = {
"Action": "Add user",
"Member": member,
"Group": group,
"Error": False,
}
log_data = {
"function": f"{__name__, sys._getframe().f_code.co_name}",
"action": "Add user",
"member": member,
"group": group,
}
try:
group_info = await auth.get_group_info(group, members=False)
can_add_remove_members = can_modify_members(
requesting_user, requesting_users_groups, group_info
)
if not can_add_remove_members:
result[
"Result"
] = "You are unable to add members to this group. Maybe it is restricted."
result["Error"] = True
error = f"There was at least one problem. {result['Result']}"
log_data["error"] = error
log.warning(log_data, exc_info=True)
return result
if not validate_email(member):
result["Result"] = "Invalid e-mail address entered"
result["Error"] = True
log_data["message"] = "Error"
log_data["error"] = result["Result"]
log.warning(log_data, exc_info=True)
return result
if (
not group_info.allow_third_party_users
and not await auth.does_user_exist(member)
):
result[
"Result"
] = "User does not exist in our environment and this group doesn't allow third party users."
result["Error"] = True
log_data["message"] = "Error"
log_data["error"] = result["Result"]
log.warning(log_data, exc_info=True)
return result
await add_user_to_group(member, group, requesting_user, service=service)
result["Result"] = "Successfully added user to group"
return result
except Exception as e:
result["Result"] = html.escape(str(e))
result["Error"] = True
error = f"There was at least one problem. {e}"
log_data["message"] = "Error"
log_data["error"] = error
log.error(log_data, exc_info=True)
return result | null |
162,107 | import asyncio
import html
import sys
from typing import Any, Dict, List, Optional, Union
import googleapiclient.discovery
import ujson as json
from asgiref.sync import sync_to_async
from google.oauth2 import service_account
from googleapiclient.discovery import Resource
from googleapiclient.errors import HttpError
from retrying import retry
from validate_email import validate_email
from consoleme.config import config
from consoleme.exceptions.exceptions import (
BackgroundCheckNotPassedException,
BulkAddPrevented,
DifferentUserGroupDomainException,
MissingConfigurationValue,
NoCredentialSubjectException,
NoGroupsException,
NotAMemberException,
UnableToModifyRestrictedGroupMembers,
UnauthorizedToAccess,
UserAlreadyAMemberOfGroupException,
)
from consoleme.lib.auth import can_modify_members
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.groups import does_group_require_bg_check
from consoleme.lib.plugins import get_plugin_by_name
stats = get_plugin_by_name(config.get("plugins.metrics", "default_metrics"))()
log = config.get_logger()
auth = get_plugin_by_name(config.get("plugins.auth", "default_auth"))()
async def remove_user_from_group(
user_email: str,
google_group_email: str,
updated_by: Optional[str] = None,
dry_run: None = None,
service: Optional[Resource] = None,
) -> Dict[str, bool]:
"""Remove user member to group."""
result = {"done": True}
dynamo = UserDynamoHandler()
function = f"{__name__}.{sys._getframe().f_code.co_name}"
stats.count(function)
log_data = {
"function": function,
"user_email": user_email,
"group": google_group_email,
"updated_by": updated_by,
"dry_run": dry_run,
"message": "Removing user from group",
}
log.debug(log_data)
group_info = await auth.get_group_info(google_group_email, members=False)
await raise_if_restricted(user_email, group_info)
if not service:
service = await get_service("admin", "directory_v1", google_group_email)
existing = await list_group_members(google_group_email, dry_run=dry_run)
if user_email in existing:
if not dry_run:
stats.count(
f"{function}.remove_user_from_group",
tags={
"user_email": user_email,
"google_group_email": google_group_email,
"updated_by": updated_by,
},
)
await delete_group_members_call(service, google_group_email, user_email)
await dynamo.create_group_log_entry(
google_group_email, user_email, updated_by, "Removed"
)
else:
log_data[
"message"
] = "Unable to remove user from group. User is not currently in the group."
log.warning(log_data)
result["done"] = False
result["message"] = log_data["message"]
raise NotAMemberException(result["message"])
return result
import asyncio
def can_modify_members(
user: str, user_groups: List[str], group_info: Optional[Any]
) -> bool:
# No users can modify members on restricted groups
if group_info and group_info.restricted:
return False
if can_admin_all(user, user_groups):
return True
if is_in_group(
user,
user_groups,
[
*config.get("groups.can_admin_restricted", []),
*config.get("dynamic_config.groups.can_admin_restricted", []),
],
):
return True
if is_in_group(
user,
user_groups,
[
*config.get("groups.can_modify_members", []),
*config.get("dynamic_config.groups.can_modify_members", []),
],
):
return True
return False
async def remove_user_from_group_task(
member: str,
group: str,
requesting_user: str,
requesting_users_groups: List[str],
semaphore=None,
service: None = None,
) -> Dict[str, Union[str, bool]]:
if not semaphore:
semaphore = asyncio.BoundedSemaphore(10)
async with semaphore:
stats.count(
"remove_user_from_group_task.attempt",
tags={"member": member, "group": group, "requesting_user": requesting_user},
)
member = member.strip()
result = {
"Action": "Remove user",
"Member": member,
"Requesting User": requesting_user,
"Group": group,
"Error": False,
}
log_data = {
"function": f"{__name__, sys._getframe().f_code.co_name}",
"action": "Remove user",
"member": member,
"group": group,
}
try:
group_info = await auth.get_group_info(group, members=False)
can_add_remove_members = can_modify_members(
requesting_user, requesting_users_groups, group_info
)
if not can_add_remove_members:
result[
"Result"
] = "You are unable to remove members from this group. Maybe it is restricted."
result["Error"] = True
error = f"There was at least one problem. {result['Result']}"
log_data["error"] = error
log.warning(log_data, exc_info=True)
return result
if not validate_email(member):
result[
"Result"
] = "Invalid e-mail address entered, or user doesn't exist"
result["Error"] = True
log_data["message"] = "Error"
log_data["error"] = result["Result"]
log.warning(log_data, exc_info=True)
return result
await remove_user_from_group(
member, group, requesting_user, service=service
)
result["Result"] = "Successfully removed user from group"
return result
except Exception as e:
result["Result"] = str(e)
result["Error"] = True
error = f"There was at least one problem. {e}"
log_data["message"] = "Error"
log_data["error"] = error
log.error(log_data, exc_info=True)
return result | null |
162,108 | import asyncio
import html
import sys
from typing import Any, Dict, List, Optional, Union
import googleapiclient.discovery
import ujson as json
from asgiref.sync import sync_to_async
from google.oauth2 import service_account
from googleapiclient.discovery import Resource
from googleapiclient.errors import HttpError
from retrying import retry
from validate_email import validate_email
from consoleme.config import config
from consoleme.exceptions.exceptions import (
BackgroundCheckNotPassedException,
BulkAddPrevented,
DifferentUserGroupDomainException,
MissingConfigurationValue,
NoCredentialSubjectException,
NoGroupsException,
NotAMemberException,
UnableToModifyRestrictedGroupMembers,
UnauthorizedToAccess,
UserAlreadyAMemberOfGroupException,
)
from consoleme.lib.auth import can_modify_members
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.groups import does_group_require_bg_check
from consoleme.lib.plugins import get_plugin_by_name
stats = get_plugin_by_name(config.get("plugins.metrics", "default_metrics"))()
log = config.get_logger()
async def get_service(service_name: str, service_path: str, group: str) -> Resource:
"""
Get a service connection to Google. You'll need to generate a GCP service account first from instructions here:
https://hawkins.gitbook.io/consoleme/configuration/authentication-and-authorization/google-groups-support
ConsoleMe requires that you either have a service key file with content like below,
and you've set the configuration for `google.service_key_file` to the full path of that file on disk,
or you've just put the json for this in your ConsoleMe configuration in the `google.service_key_dict` configuration
key.
There are sensitive secrets here, so if you want to
reference them directly in configuration, we encourage you to store these secrets in AWS Secrets Manager
https://hawkins.gitbook.io/consoleme/configuration/aws-secret-manager-integration
{
"type": "service_account",
"project_id": "cons...",
"private_key_id": "dc61.....",
"private_key": "-----BEGIN PRIVATE KEY-----\nMII.....",
"client_email": "cons...@cons....gserviceaccount.com",
"client_id": "1234....",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/consolem...."
}
"""
function = f"{__name__}.{sys._getframe().f_code.co_name}"
stats.count(function)
log_data = {
"function": function,
"service_name": service_name,
"service_path": service_path,
"group": group,
"message": f"Building service connection for {service_name} / {service_path}",
}
log.debug(log_data)
if config.get("google.service_key_file"):
admin_credentials = service_account.Credentials.from_service_account_file(
config.get("google.service_key_file"),
scopes=config.get(
"google.admin_scopes",
["https://www.googleapis.com/auth/admin.directory.group"],
),
)
elif config.get("google.service_key_dict"):
admin_credentials = service_account.Credentials.from_service_account_info(
config.get("google.service_key_dict"),
scopes=config.get(
"google.admin_scopes",
["https://www.googleapis.com/auth/admin.directory.group"],
),
)
else:
raise MissingConfigurationValue(
"Missing configuration for Google. You must configure either `google.service_key_file` "
"or `google.service_key_dict`."
)
# Change credential subject based on group domain
credential_subjects = config.get("google.credential_subject")
credential_subject = None
for k, v in credential_subjects.items():
if k == group.split("@")[1]:
credential_subject = v
break
if not credential_subject:
raise NoCredentialSubjectException(
"Error: Unable to find Google credential subject for domain {}. "
"{}".format(group.split("@")[1], config.get("ses.support_reference", ""))
)
admin_delegated_credentials = admin_credentials.with_subject(credential_subject)
service = await sync_to_async(googleapiclient.discovery.build)(
service_name, service_path, credentials=admin_delegated_credentials
)
return service
def list_user_groups_call(service, user_email, page_token=None):
if page_token:
results = (
service.groups().list(userKey=user_email, pageToken=page_token).execute()
)
else:
results = service.groups().list(userKey=user_email).execute()
return results
The provided code snippet includes necessary dependencies for implementing the `get_group_memberships` function. Write a Python function `async def get_group_memberships(user_email, dry_run=None, service=None)` to solve the following problem:
Get group memberships for a user
Here is the function:
async def get_group_memberships(user_email, dry_run=None, service=None):
"""Get group memberships for a user"""
function = f"{__name__}.{sys._getframe().f_code.co_name}"
stats.count(function)
log_data = {
"function": function,
"user": user_email,
"message": "Getting list of groups for user",
}
log.debug(log_data)
if not service:
service = await get_service("admin", "directory_v1", user_email)
groups = []
if not dry_run:
try:
page_token = None
while True:
results = await list_user_groups_call(service, user_email, page_token)
for g in results.get("groups"):
groups.append(g.get("email"))
page_token = results.get("nextPageToken")
if not page_token:
break
except HttpError as he:
errors = json.loads(he.content.decode())
log.debug(errors)
raise he
return groups
return [] | Get group memberships for a user |
162,109 | import asyncio
import html
import sys
from typing import Any, Dict, List, Optional, Union
import googleapiclient.discovery
import ujson as json
from asgiref.sync import sync_to_async
from google.oauth2 import service_account
from googleapiclient.discovery import Resource
from googleapiclient.errors import HttpError
from retrying import retry
from validate_email import validate_email
from consoleme.config import config
from consoleme.exceptions.exceptions import (
BackgroundCheckNotPassedException,
BulkAddPrevented,
DifferentUserGroupDomainException,
MissingConfigurationValue,
NoCredentialSubjectException,
NoGroupsException,
NotAMemberException,
UnableToModifyRestrictedGroupMembers,
UnauthorizedToAccess,
UserAlreadyAMemberOfGroupException,
)
from consoleme.lib.auth import can_modify_members
from consoleme.lib.dynamo import UserDynamoHandler
from consoleme.lib.groups import does_group_require_bg_check
from consoleme.lib.plugins import get_plugin_by_name
auth = get_plugin_by_name(config.get("plugins.auth", "default_auth"))()
async def add_user_to_group(
user_email: str,
google_group_email: str,
updated_by: Optional[str] = None,
role: str = "MEMBER",
dry_run: None = None,
service: Optional[Resource] = None,
request: Optional[Dict[str, Union[int, str]]] = None,
) -> Dict[str, bool]:
"""Add user member to group."""
dynamo = UserDynamoHandler()
result = {"done": True}
function = f"{__name__}.{sys._getframe().f_code.co_name}"
stats.count(function)
log_data = {
"function": function,
"user_email": user_email,
"google_group_email": google_group_email,
"updated_by": updated_by,
"role": role,
"dry_run": dry_run,
"message": "Adding user to group",
}
if not service:
service = await get_service("admin", "directory_v1", google_group_email)
existing = await list_group_members(google_group_email, dry_run=dry_run)
if user_email in existing:
log_data["message"] = "Unable to add user to group. User is already a member."
log.warning(log_data)
result["done"] = False
result["message"] = log_data["message"]
raise UserAlreadyAMemberOfGroupException(result["message"])
group_info = await auth.get_group_info(google_group_email, members=False)
await raise_if_requires_bgcheck_and_no_bgcheck(user_email, group_info)
await raise_if_not_same_domain(user_email, group_info)
await raise_if_restricted(user_email, group_info)
await raise_if_bulk_add_disabled_and_no_request(group_info, request)
if not dry_run:
stats.count(
"google.add_user_to_group",
tags={
"user_email": user_email,
"google_group_email": google_group_email,
"updated_by": updated_by,
},
)
await insert_group_members_call(service, google_group_email, user_email, role)
await dynamo.create_group_log_entry(
google_group_email, user_email, updated_by, "Added"
)
log.info(log_data)
return result
class NoGroupsException(BaseException):
"""NoGroupsException."""
def __init__(self, msg=""):
stats.count("NoGroupsException")
super().__init__(msg)
class UserAlreadyAMemberOfGroupException(BaseException):
"""Unable to add a user to a group that they're already a member of."""
def __init__(self, msg=""):
stats.count("UserAlreadyAMemberOfGroupException")
super().__init__(msg)
class BulkAddPrevented(BaseException):
"""Bulk adding user to group is prevented"""
def __init__(self, msg=""):
stats.count("BulkAddPrevented")
super().__init__(msg)
class UnauthorizedToAccess(BaseException):
"""Unauthorized to access resource"""
def __init__(self, msg=""):
stats.count("UnauthorizedToViewPage")
super().__init__(msg)
def can_modify_members(
user: str, user_groups: List[str], group_info: Optional[Any]
) -> bool:
# No users can modify members on restricted groups
if group_info and group_info.restricted:
return False
if can_admin_all(user, user_groups):
return True
if is_in_group(
user,
user_groups,
[
*config.get("groups.can_admin_restricted", []),
*config.get("dynamic_config.groups.can_admin_restricted", []),
],
):
return True
if is_in_group(
user,
user_groups,
[
*config.get("groups.can_modify_members", []),
*config.get("dynamic_config.groups.can_modify_members", []),
],
):
return True
return False
class UserDynamoHandler(BaseDynamoHandler):
def __init__(self, user_email: Optional[str] = None) -> None:
try:
self.requests_table = self._get_dynamo_table(
config.get("aws.requests_dynamo_table", "consoleme_requests_global")
)
self.users_table = self._get_dynamo_table(
config.get("aws.users_dynamo_table", "consoleme_users_global")
)
self.group_log = self._get_dynamo_table(
config.get("aws.group_log_dynamo_table", "consoleme_audit_global")
)
self.dynamic_config = self._get_dynamo_table(
config.get("aws.group_log_dynamo_table", "consoleme_config_global")
)
self.policy_requests_table = self._get_dynamo_table(
config.get(
"aws.policy_requests_dynamo_table", "consoleme_policy_requests"
)
)
self.api_health_roles_table = self._get_dynamo_table(
config.get(
"aws.api_health_apps_table_dynamo_table",
"consoleme_api_health_apps",
)
)
self.resource_cache_table = self._get_dynamo_table(
config.get(
"aws.resource_cache_dynamo_table", "consoleme_resource_cache"
)
)
self.cloudtrail_table = self._get_dynamo_table(
config.get("aws.cloudtrail_table", "consoleme_cloudtrail")
)
self.notifications_table = self._get_dynamo_table(
config.get("aws.notifications_table", "consoleme_notifications")
)
if user_email:
self.user = self.get_or_create_user(user_email)
self.affected_user = self.user
except Exception:
if config.get("development"):
log.error(
"Unable to connect to Dynamo. Trying to set user via development configuration",
exc_info=True,
)
self.user = self.sign_request(
{
"last_updated": int(time.time()),
"username": user_email,
"requests": [],
}
)
self.affected_user = self.user
else:
log.error("Unable to get Dynamo table.", exc_info=True)
raise
def write_resource_cache_data(self, data):
self.parallel_write_table(
self.resource_cache_table, data, ["resourceId", "resourceType"]
)
async def get_dynamic_config_yaml(self) -> bytes:
"""Retrieve dynamic configuration yaml."""
return await sync_to_async(self.get_dynamic_config_yaml_sync)()
def get_dynamic_config_yaml_sync(self) -> bytes:
"""Retrieve dynamic configuration yaml synchronously"""
c = b""
try:
current_config = self.dynamic_config.get_item(Key={"id": "master"})
if not current_config:
return c
compressed_config = current_config.get("Item", {}).get("config", "")
if not compressed_config:
return c
c = zlib.decompress(compressed_config.value)
except Exception: # noqa
sentry_sdk.capture_exception()
return c
def get_dynamic_config_dict(self) -> dict:
"""Retrieve dynamic configuration dictionary that can be merged with primary configuration dictionary."""
try:
loop = asyncio.get_running_loop()
except RuntimeError: # if cleanup: 'RuntimeError: There is no current event loop..'
loop = None
if loop and loop.is_running():
current_config_yaml = self.get_dynamic_config_yaml_sync()
else:
current_config_yaml = asyncio.run(self.get_dynamic_config_yaml())
config_d = yaml.safe_load(current_config_yaml)
return config_d
async def get_all_api_health_alerts(self) -> list:
"""Return all requests. If a status is specified, only requests with the specified status will be returned.
:param status:
:return:
"""
response: dict = self.api_health_roles_table.scan()
items = response.get("Items", [])
while "LastEvaluatedKey" in response:
response = self.api_health_roles_table.scan(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def get_api_health_alert_app(self, app_name) -> dict:
resp: dict = await sync_to_async(self.api_health_roles_table.get_item)(
Key={"appName": app_name}
)
return resp.get("Item", None)
async def write_api_health_alert_info(self, request, user_email: str):
"""
Writes a health alert role to the appropriate DynamoDB table
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
# enrich request
request["app_create_time"]: int = int(time.time())
request["updated_by"]: str = user_email
request["last_updated"]: int = int(time.time())
try:
await sync_to_async(self.api_health_roles_table.put_item)(
Item=self._data_to_dynamo_replace(request)
)
except Exception:
error = {
"message": "Unable to add new api_health info request",
"request": request,
"function": function,
}
log.error(error, exc_info=True)
raise
return request
async def update_api_health_alert_info(
self, request: dict, user_email=None, update_by=None, last_updated=None
):
"""
Update api_health_alert_info by roleName
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
# enrich request
if update_by:
request["updated_by"] = update_by
else:
request["updated_by"] = user_email
if last_updated:
request["last_updated"] = last_updated
else:
request["last_updated"] = int(time.time())
try:
await sync_to_async(self.api_health_roles_table.put_item)(
Item=self._data_to_dynamo_replace(request)
)
except Exception as e:
error: dict = {
"function": function,
"message": "Unable to update api_health_info request",
"request": request,
"error": str(e),
}
log.error(error, exc_info=True)
raise Exception(error)
return request
async def delete_api_health_alert_info(self, app: str) -> None:
"""
Delete api_health_alert_info by roleName
"""
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
try:
await sync_to_async(self.api_health_roles_table.delete_item)(
Key={"appName": app}
)
except Exception:
error: dict = {
"function": function,
"message": "Unable to delete api_health info",
"app": app,
}
log.error(error, exc_info=True)
raise
async def write_policy_request(
self,
user_email: str,
justification: str,
arn: str,
policy_name: str,
policy_changes: dict,
resources: List[str],
resource_policies: List[Dict],
request_time: int = None,
request_uuid=None,
policy_status="pending",
cross_account_request: bool = False,
dry_run: bool = False,
):
"""
Writes a policy request to the appropriate DynamoDB table
dry_run will create the request format, but won't actually write it
Sample run:
write_policy_request(policy_changes)
"""
request_time = request_time or int(time.time())
# Craft the new request json
timestamp = int(time.time())
request_id = request_uuid or str(uuid.uuid4())
new_request = {
"request_id": request_id,
"arn": arn,
"status": policy_status,
"justification": justification,
"request_time": request_time,
"updated_by": user_email,
"last_updated": timestamp,
"username": user_email,
"policy_name": policy_name,
"policy_changes": json.dumps(policy_changes),
"resources": resources,
"resource_policies": resource_policies,
"cross_account_request": cross_account_request,
}
if not dry_run:
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(new_request)
)
except Exception as e:
error = f"Unable to add new policy request: {new_request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
else:
log_data = {
"function": f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}",
"request": new_request,
"message": "Dry run, skipping adding request to dynamo",
}
log.debug(log_data)
return new_request
async def write_policy_request_v2(self, extended_request: ExtendedRequestModel):
"""
Writes a policy request v2 to the appropriate DynamoDB table
Sample run:
write_policy_request_v2(request)
"""
new_request = {
"request_id": extended_request.id,
"principal": extended_request.principal.dict(),
"status": extended_request.request_status.value,
"justification": extended_request.justification,
"request_time": extended_request.timestamp,
"last_updated": int(time.time()),
"version": "2",
"extended_request": json.loads(extended_request.json()),
"username": extended_request.requester_email,
}
if extended_request.principal.principal_type == "AwsResource":
new_request["arn"] = extended_request.principal.principal_arn
elif extended_request.principal.principal_type == "HoneybeeAwsResourceTemplate":
repository_name = extended_request.principal.repository_name
resource_identifier = extended_request.principal.resource_identifier
new_request["arn"] = f"{repository_name}-{resource_identifier}"
else:
raise Exception("Invalid principal type")
log_data = {
"function": f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}",
"message": "Writing policy request v2 to Dynamo",
"request": new_request,
}
log.debug(log_data)
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(new_request)
)
log_data[
"message"
] = "Successfully finished writing policy request v2 to Dynamo"
log.debug(log_data)
except Exception as e:
log_data["message"] = "Error occurred writing policy request v2 to Dynamo"
log_data["error"] = str(e)
log.error(log_data, exc_info=True)
error = f"{log_data['message']}: {str(e)}"
raise Exception(error)
return new_request
async def update_policy_request(self, updated_request):
"""
Update a policy request by request ID
Sample run:
update_policy_request(policy_changes)
"""
updated_request["last_updated"] = int(time.time())
try:
await sync_to_async(self.policy_requests_table.put_item)(
Item=self._data_to_dynamo_replace(updated_request)
)
except Exception as e:
error = f"Unable to add updated policy request: {updated_request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return updated_request
async def get_policy_requests(self, arn=None, request_id=None):
"""Reads a policy request from the appropriate DynamoDB table"""
if not arn and not request_id:
raise Exception("Must pass in ARN or policy request ID")
if request_id:
requests = self.policy_requests_table.query(
KeyConditionExpression="request_id = :ri",
ExpressionAttributeValues={":ri": request_id},
)
else:
requests = self.policy_requests_table.query(
KeyConditionExpression="arn = :arn",
ExpressionAttributeValues={":arn": arn},
)
matching_requests = []
if requests["Items"]:
items = self._data_from_dynamo_replace(requests["Items"])
items = await self.convert_policy_requests_to_v3(items)
matching_requests.extend(items)
return matching_requests
async def convert_policy_requests_to_v3(self, requests):
# Remove this function and calls to this function after a grace period of
changed = False
for request in requests:
if not request.get("version") in ["2"]:
continue
if request.get("extended_request") and not request.get("principal"):
principal_arn = request.pop("arn")
request["principal"] = {
"principal_arn": principal_arn,
"principal_type": "AwsResource",
}
request["extended_request"]["principal"] = {
"principal_arn": principal_arn,
"principal_type": "AwsResource",
}
request.pop("arn", None)
changes = (
request.get("extended_request", {})
.get("changes", {})
.get("changes", [])
)
for change in changes:
if not change.get("principal_arn"):
continue
if not change.get("version") in ["2.0", "2", 2]:
continue
change["principal"] = {
"principal_arn": change["principal_arn"],
"principal_type": "AwsResource",
}
change.pop("principal_arn")
change["version"] = "3.0"
changed = True
if changed:
self.parallel_write_table(self.policy_requests_table, requests)
return requests
async def get_all_policy_requests(
self, status: Optional[str] = "pending"
) -> List[Dict[str, Union[int, List[str], str]]]:
"""Return all policy requests. If a status is specified, only requests with the specified status will be
returned.
:param status:
:return:
"""
requests = await sync_to_async(self.parallel_scan_table)(
self.policy_requests_table
)
requests = await self.convert_policy_requests_to_v3(requests)
return_value = []
if status:
for item in requests:
if status and item["status"] == status:
return_value.append(item)
else:
return_value = requests
return return_value
async def update_dynamic_config(self, config: str, updated_by: str) -> None:
"""Take a YAML config and writes to DDB (The reason we use YAML instead of JSON is to preserve comments)."""
# Validate that config loads as yaml, raises exception if not
yaml.safe_load(config)
stats.count("update_dynamic_config", tags={"updated_by": updated_by})
current_config_entry = self.dynamic_config.get_item(Key={"id": "master"})
if current_config_entry.get("Item"):
old_config = {
"id": current_config_entry["Item"]["updated_at"],
"updated_by": current_config_entry["Item"]["updated_by"],
"config": current_config_entry["Item"]["config"],
"updated_at": str(int(time.time())),
}
self.dynamic_config.put_item(Item=self._data_to_dynamo_replace(old_config))
new_config = {
"id": "master",
"config": zlib.compress(config.encode()),
"updated_by": updated_by,
"updated_at": str(int(time.time())),
}
self.dynamic_config.put_item(Item=self._data_to_dynamo_replace(new_config))
def validate_signature(self, items):
signature = items.pop("signature")
if isinstance(signature, Binary):
signature = signature.value
json_request = json.dumps(items, sort_keys=True)
if not crypto.verify(json_request, signature):
raise Exception(f"Invalid signature for request: {json_request}")
def sign_request(
self, user_entry: Dict[str, Union[Decimal, List[str], Binary, str]]
) -> Dict[str, Union[Decimal, List[str], str, bytes]]:
"""
Sign the request and returned request with signature
:param user_entry:
:return:
"""
# Remove old signature if it exists
user_entry.pop("signature", None)
user_entry = self._data_from_dynamo_replace(user_entry)
json_request = json.dumps(user_entry, sort_keys=True, use_decimal=True)
sig = crypto.sign(json_request)
user_entry["signature"] = sig
return user_entry
async def authenticate_user(self, login_attempt) -> AuthenticationResponse:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {
"function": function,
"user_email": login_attempt.username,
"after_redirect_uri": login_attempt.after_redirect_uri,
}
user_entry = await sync_to_async(self.users_table.query)(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": login_attempt.username},
)
user = None
generic_error = ["User doesn't exist, or password is incorrect. "]
if user_entry and "Items" in user_entry and len(user_entry["Items"]) == 1:
user = user_entry["Items"][0]
if not user:
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = f"Unable to find user: {login_attempt.username}"
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
if not user.get("password"):
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = "User exists, but doesn't have a password stored in the database"
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
password_hash_matches = bcrypt.checkpw(
login_attempt.password.encode("utf-8"), user["password"].value
)
if not password_hash_matches:
delay_error = await wait_after_authentication_failure(
login_attempt.username
)
error = "Password does not match. "
log.error({**log_data, "message": error + delay_error})
return AuthenticationResponse(
authenticated=False, errors=generic_error + [delay_error]
)
return AuthenticationResponse(
authenticated=True, username=user["username"], groups=user["groups"]
)
def create_user(
self,
user_email,
password: Optional[str] = None,
groups: Optional[List[str]] = None,
):
if not groups:
groups = []
timestamp = int(time.time())
unsigned_user_entry = {
"created": timestamp,
"last_updated": timestamp,
"username": user_email,
"requests": [],
"groups": groups,
}
if password:
pw = bytes(password, "utf-8")
salt = bcrypt.gensalt()
unsigned_user_entry["password"] = bcrypt.hashpw(pw, salt)
user_entry = self.sign_request(unsigned_user_entry)
try:
self.users_table.put_item(Item=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to add user submission: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return user_entry
def update_user(
self,
user_email,
password: Optional[str] = None,
groups: Optional[List[str]] = None,
):
if not groups:
groups = []
user_ddb = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
user = None
if user_ddb and "Items" in user_ddb and len(user_ddb["Items"]) == 1:
user = user_ddb["Items"][0]
if not user:
raise DataNotRetrievable(f"Unable to find user: {user_email}")
timestamp = int(time.time())
if password:
pw = bytes(password, "utf-8")
salt = bcrypt.gensalt()
user["password"] = bcrypt.hashpw(pw, salt)
if groups:
user["groups"] = groups
user["last_updated"] = timestamp
user_entry = self.sign_request(user)
try:
self.users_table.put_item(Item=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to add user submission: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return user_entry
def delete_user(self, user_email):
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user_entry = {"username": user_email}
try:
self.users_table.delete_item(Key=self._data_to_dynamo_replace(user_entry))
except Exception as e:
error = f"Unable to delete user: {user_entry}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
async def get_user(
self, user_email: str
) -> Optional[Dict[str, Union[Decimal, List[str], Binary, str]]]:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
if user and "Items" in user and len(user["Items"]) == 1:
return user["Items"][0]
return None
def get_or_create_user(
self, user_email: str
) -> Dict[str, Union[Decimal, List[str], Binary, str]]:
function: str = (
f"{__name__}.{self.__class__.__name__}.{sys._getframe().f_code.co_name}"
)
log_data = {"function": function, "user_email": user_email}
log.debug(log_data)
user = self.users_table.query(
KeyConditionExpression="username = :un",
ExpressionAttributeValues={":un": user_email},
)
items = []
if user and "Items" in user:
items = user["Items"]
if not items:
return self.create_user(user_email)
return items[0]
def resolve_request_ids(
self, request_ids: List[str]
) -> List[Dict[str, Union[int, str]]]:
requests = []
for request_id in request_ids:
request = self.requests_table.query(
KeyConditionExpression="request_id = :ri",
ExpressionAttributeValues={":ri": request_id},
)
if request["Items"]:
items = self._data_from_dynamo_replace(request["Items"])
requests.append(items[0])
else:
raise NoMatchingRequest(
f"No matching request for request_id: {request_id}"
)
return requests
def add_request_id_to_user(
self,
affected_user: Dict[str, Union[Decimal, List[str], Binary, str]],
request_id: str,
) -> None:
affected_user["requests"].append(request_id)
self.users_table.put_item(
Item=self._data_to_dynamo_replace(self.sign_request(affected_user))
)
def add_request(
self,
user_email: str,
group: str,
justification: str,
request_time: None = None,
status: str = "pending",
updated_by: Optional[str] = None,
) -> Dict[str, Union[int, str]]:
"""
Add a user request to the dynamo table
Sample run:
add_request("user@example.com", "engtest", "because")
:param user_email: Email address of user
:param group: Name of group user is requesting access to
:param justification:
:param request_id:
:param request_time:
:param status:
:param updated_by:
:return:
"""
"""
Request:
group
justification
role
request_time
approval_time
updated_by
approval_reason
status
user@example.com:
requests: []
last_updated: 1
signature: xxxx
#pending: []
#expired: []
# How to expire requests if soemeone maliciously deletes content
# How to query for all approved requests for group X
# What if we want to send email saying your request is expiring in 7 days? Maybe celery to query all
# What about concept of request ID? Maybe base64 encoded thing?
# Need an all-in-one page to show all pending requests, all expired/approved requests
"""
request_time = request_time or int(time.time())
stats.count("new_group_request", tags={"user": user_email, "group": group})
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
# Get current user. Create if they do not already exist
# self.user = self.get_or_create_user(user_email)
# Get current user requests, which will validate existing signature
# existing_request_ids = self.user["requests"]
# existing_requests = self.resolve_request_ids(existing_request_ids)
existing_pending_requests_for_group = self.get_requests_by_user(
user_email, group, status="pending"
)
# Craft the new request json
timestamp = int(time.time())
request_id = str(uuid.uuid4())
new_request = {
"request_id": request_id,
"group": group,
"status": status,
"justification": justification,
"request_time": request_time,
"updated_by": updated_by,
"last_updated": timestamp,
"username": user_email,
}
# See if user already has an active or pending request for the group
if existing_pending_requests_for_group:
for request in existing_pending_requests_for_group:
raise PendingRequestAlreadyExists(
f"Pending request for group: {group} already exists: {request}"
)
try:
self.requests_table.put_item(Item=self._data_to_dynamo_replace(new_request))
except Exception as e:
error = {
"error": f"Unable to add user request: {str(e)}",
"request": new_request,
}
log.error(error, exc_info=True)
raise Exception(error)
self.add_request_id_to_user(self.affected_user, request_id)
return new_request
async def get_all_requests(self, status=None):
"""Return all requests. If a status is specified, only requests with the specified status will be returned.
:param status:
:return:
"""
items = await sync_to_async(self.parallel_scan_table)(self.requests_table)
return_value = []
if status:
for item in items:
new_json = []
for j in item["json"]:
if j["status"] == status:
new_json.append(j)
item["json"] = new_json
if new_json:
return_value.append(item)
else:
return_value = items
return return_value
def get_requests_by_user(
self,
user_email: str,
group: str = None,
status: str = None,
use_cache: bool = False,
) -> dict:
"""Get requests by user. Group and status can also be specified to filter results.
:param user_email:
:param group:
:param status:
:return:
"""
red_key = f"USER_REQUESTS_{user_email}-{group}-{status}"
if use_cache:
requests_to_return = red.get(red_key)
if requests_to_return:
return json.loads(requests_to_return)
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
existing_request_ids = self.affected_user["requests"]
existing_requests = self.resolve_request_ids(existing_request_ids)
requests_to_return = []
if existing_requests:
for request in existing_requests:
if group and request["group"] != group:
continue
if status and request["status"] != status:
continue
requests_to_return.append(request)
if use_cache:
red.setex(red_key, 120, json.dumps(requests_to_return))
return requests_to_return
def change_request_status(
self, user_email, group, new_status, updated_by=None, reviewer_comments=None
):
"""
:param user:
:param status:
:param request_id:
:return:
"""
stats.count(
"update_group_request",
tags={
"user": user_email,
"group": group,
"new_status": new_status,
"updated_by": updated_by,
},
)
modified_request = None
if self.affected_user.get("username") != user_email:
self.affected_user = self.get_or_create_user(user_email)
timestamp = int(time.time())
if new_status not in POSSIBLE_STATUSES:
raise Exception(
f"Invalid status. Status must be one of {POSSIBLE_STATUSES}"
)
if new_status == "approved" and not updated_by:
raise Exception(
"You must provide `updated_by` to change a request status to approved."
)
existing_requests = self.get_requests_by_user(user_email)
if existing_requests:
updated = False
for request in existing_requests:
if request["group"] == group:
request["updated_by"] = updated_by
request["status"] = new_status
request["last_updated"] = timestamp
request["reviewer_comments"] = reviewer_comments
modified_request = request
try:
self.requests_table.put_item(
Item=self._data_to_dynamo_replace(request)
)
except Exception as e:
error = f"Unable to add user request: {request}: {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
updated = True
if not updated:
raise NoExistingRequest(
f"Unable to find existing request for user: {user_email} and group: {group}."
)
else:
raise NoExistingRequest(
f"Unable to find existing requests for user: {user_email}"
)
return modified_request
def change_request_status_by_id(
self,
request_id: str,
new_status: str,
updated_by: Optional[str] = None,
reviewer_comments: Optional[str] = None,
) -> Dict[str, Union[int, str]]:
"""
Change request status by ID
:param request_id:
:param new_status:
:param updated_by:
:return: new requests
"""
modified_request = None
if new_status == "approved" and not updated_by:
raise Exception(
"You must provide `updated_by` to change a request status to approved."
)
requests = self.resolve_request_ids([request_id])
if new_status not in POSSIBLE_STATUSES:
raise Exception(
f"Invalid status. Status must be one of {POSSIBLE_STATUSES}"
)
for request in requests:
request["status"] = new_status
request["updated_by"] = updated_by
request["last_updated"] = int(time.time())
request["reviewer_comments"] = reviewer_comments
modified_request = request
try:
self.requests_table.put_item(Item=self._data_to_dynamo_replace(request))
except Exception as e:
error = f"Unable to add user request: {request} : {str(e)}"
log.error(error, exc_info=True)
raise Exception(error)
return modified_request
def get_all_policies(self):
"""Return all policies."""
response = self.policies_table.scan()
items = []
if response and "Items" in response:
items = self._data_from_dynamo_replace(response["Items"])
while "LastEvaluatedKey" in response:
response = self.policies_table.scan(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def create_group_log_entry(
self,
group: str,
username: str,
updated_by: str,
action: str,
updated_at: None = None,
extra: None = None,
) -> None:
updated_at = updated_at or int(time.time())
log_id = str(uuid.uuid4())
log_entry = {
"uuid": log_id,
"group": group,
"username": username,
"updated_by": updated_by,
"updated_at": updated_at,
"action": action,
"extra": extra,
}
self.group_log.put_item(Item=self._data_to_dynamo_replace(log_entry))
async def get_all_audit_logs(self) -> List[Dict[str, Union[int, None, str]]]:
response = await sync_to_async(self.group_log.scan)()
items = []
if response and "Items" in response:
items = self._data_from_dynamo_replace(response["Items"])
while "LastEvaluatedKey" in response:
response = await sync_to_async(self.group_log.scan)(
ExclusiveStartKey=response["LastEvaluatedKey"]
)
items.extend(self._data_from_dynamo_replace(response["Items"]))
return items
async def get_all_pending_requests(self):
return await self.get_all_requests(status="pending")
def batch_write_cloudtrail_events(self, items):
with self.cloudtrail_table.batch_writer(
overwrite_by_pkeys=["arn", "request_id"]
) as batch:
for item in items:
batch.put_item(Item=self._data_to_dynamo_replace(item))
return True
async def get_top_cloudtrail_errors_by_arn(self, arn, n=5):
response: dict = await sync_to_async(self.cloudtrail_table.query)(
KeyConditionExpression=Key("arn").eq(arn)
)
items = response.get("Items", [])
aggregated_errors = defaultdict(dict)
for item in items:
if int(item["ttl"]) < int(time.time()):
continue
event_call = item["event_call"]
event_resource = item.get("resource", "")
event_string = f"{event_call}|||{event_resource}"
if not aggregated_errors.get(event_string):
aggregated_errors[event_string]["count"] = 0
aggregated_errors[event_string]["generated_policy"] = item.get(
"generated_policy", {}
)
aggregated_errors[event_string]["count"] += 1
top_n_errors = {
k: v
for k, v in sorted(
aggregated_errors.items(),
key=lambda item: item[1]["count"],
reverse=True,
)[:n]
}
return top_n_errors
def count_arn_errors(self, error_count, items):
for item in items:
arn = item.get("arn")
if not error_count.get(arn):
error_count[arn] = 0
error_count[arn] += item.get("count", 1)
return error_count
async def api_add_user_to_group_or_raise(group_name, member_name, actor):
try:
group_info = await auth.get_group_info(group_name, members=False)
except Exception:
raise NoGroupsException("Unable to retrieve the specified group")
actor_groups = await auth.get_groups(actor)
can_add_remove_members = can_modify_members(actor, actor_groups, group_info)
if not can_add_remove_members:
raise UnauthorizedToAccess("Unauthorized to modify members of this group.")
try:
await add_user_to_group(member_name, group_name, actor)
except HttpError as e:
# Inconsistent GG API error - ignore failure for user already existing
if e.resp.reason == "duplicate":
pass
except UserAlreadyAMemberOfGroupException:
pass
except BulkAddPrevented:
dynamo_handler = UserDynamoHandler(actor)
dynamo_handler.add_request(
member_name,
group_name,
f"{actor} requesting on behalf of {member_name} from a bulk operation",
updated_by=actor,
)
return "REQUESTED"
return "ADDED" | null |
162,110 | import sys
import boto3
import ujson as json
from asgiref.sync import sync_to_async
from botocore.exceptions import ClientError
from consoleme.config import config
from consoleme.lib.plugins import get_plugin_by_name
stats = get_plugin_by_name(config.get("plugins.metrics", "default_metrics"))()
log = config.get_logger()
async def decode_duo_response_from_lambda(response, username):
"""Decode the response from the Duo lambda."""
result = json.loads(response["Payload"].read().decode("utf-8"))
if not result:
return False
if result.get("duo_auth", "") == "success":
stats.count("duo.mfa_request.approve", tags={"user": username})
return True
stats.count("duo.mfa_request.deny", tags={"user": username})
return False
The provided code snippet includes necessary dependencies for implementing the `duo_mfa_user` function. Write a Python function `async def duo_mfa_user(username, message="ConsoleMe Authorization Request")` to solve the following problem:
Send a DUO mfa push request to user.
Here is the function:
async def duo_mfa_user(username, message="ConsoleMe Authorization Request"):
"""Send a DUO mfa push request to user."""
# Create session for the region deployed in.
session = boto3.Session(region_name=config.region)
# Create lambda client
client = session.client("lambda")
# Generate the payload for the event passed to the lambda function
payload = {"username": username, "message_type": message}
lambda_arn = config.get("duo.lambda_arn", None)
log_data = {"function": f"{__name__}.{sys._getframe().f_code.co_name}"}
if lambda_arn:
try:
# Invoke the Lambda Function that will send a DUO Push to the user
response = await sync_to_async(client.invoke)(
FunctionName=lambda_arn.format(config.region),
InvocationType="RequestResponse",
Payload=bytes(json.dumps(payload), "utf-8"),
)
stats.count("duo.mfa_request", tags={"user": username})
except ClientError as e:
log_data["error"] = e.response.get("Error", {}).get(
"Message", "Unknown error in Duo Lambda invoke"
)
log.error(log_data, exc_info=True)
# We had an error so we should deny this request
return False
log_data["message"] = "Duo MFA request sent to {}".format(username)
log.info(log_data)
# Decode and return the result
return await decode_duo_response_from_lambda(response, username) | Send a DUO mfa push request to user. |
162,111 | from pydantic import BaseModel as PydanticBaseModel
The provided code snippet includes necessary dependencies for implementing the `to_camel` function. Write a Python function `def to_camel(string)` to solve the following problem:
Convert a snake_case string to CamelCase
Here is the function:
def to_camel(string):
"""Convert a snake_case string to CamelCase"""
return "".join(word.capitalize() for word in string.split("_")) | Convert a snake_case string to CamelCase |
162,112 | from datetime import datetime
import pytz
import ujson as json
from asgiref.sync import async_to_sync
from consoleme.config import config
from consoleme.lib.redis import RedisHandler
red = async_to_sync(RedisHandler().redis)()
async def delete_expired_challenges(all_challenges):
current_time = int(datetime.utcnow().replace(tzinfo=pytz.UTC).timestamp())
expired_challenge_tokens = []
for token, challenge_j in all_challenges.items():
challenge = json.loads(challenge_j)
if challenge.get("ttl", 0) < current_time:
expired_challenge_tokens.append(token)
if expired_challenge_tokens:
red.hdel(
config.get("challenge_url.redis_key", "TOKEN_CHALLENGES_TEMP"),
*expired_challenge_tokens,
) | null |
162,113 | from datetime import datetime
import pytz
import ujson as json
from asgiref.sync import async_to_sync
from consoleme.config import config
from consoleme.lib.redis import RedisHandler
log = config.get_logger()
red = async_to_sync(RedisHandler().redis)()
async def retrieve_user_challenge(request, requested_challenge_token, log_data):
current_time = int(datetime.utcnow().replace(tzinfo=pytz.UTC).timestamp())
# Get fresh challenge for user's request
user_challenge_j = red.hget(
config.get("challenge_url.redis_key", "TOKEN_CHALLENGES_TEMP"),
requested_challenge_token,
)
if not user_challenge_j:
message = "The requested challenge URL was not found. Please try requesting a new challenge URL."
request.write({"message": message})
return
# Do a double-take check on the ttl
# Delete the token
user_challenge = json.loads(user_challenge_j)
if user_challenge.get("ttl", 0) < current_time:
message = (
"This challenge URL has expired. Please try requesting a new challenge URL."
)
request.write({"message": message})
return
if request.user != user_challenge.get("user"):
log_data = {
**log_data,
"message": "Authenticated user is different then user that requested token",
"authenticated_user": request.user,
"challenge_user": user_challenge.get("user"),
}
log.error(log_data)
message = (
"This challenge URL is associated with a different user. Ensure that your client "
"configuration is specifying the correct user."
)
request.write({"message": message})
return
return user_challenge | null |
162,114 | from datetime import datetime, timedelta
from secrets import token_urlsafe
import jwt
from asgiref.sync import sync_to_async
from consoleme.config import config
jwt_secret = config.get("jwt_secret")
if not jwt_secret:
jwt_secret = token_urlsafe(16)
log.error(
{
"message": "Configuration key `jwt.secret` is not set. Setting a random secret"
}
)
import jwt
async def validate_and_return_jwt_token(auth_cookie):
try:
decoded_jwt = jwt.decode(auth_cookie, jwt_secret, algorithms="HS256")
email = decoded_jwt.get(config.get("jwt.attributes.email", "email"))
groups = decoded_jwt.get(config.get("jwt.attributes.groups", "groups"), [])
exp = decoded_jwt.get("exp")
return {
"user": email,
"groups": groups,
"iat": decoded_jwt.get("iat"),
"exp": exp,
}
except (jwt.ExpiredSignatureError, jwt.InvalidSignatureError, jwt.DecodeError):
# Force user to reauth.
return False | null |
162,115 | import base64
import re
import sys
import time
import urllib
from collections import defaultdict
from typing import Dict, List
import ujson as json
from deepdiff import DeepDiff
from policy_sentry.util.actions import get_service_from_action
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
ResourceNotFound,
)
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_service_from_arn,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.role_updater.handler import update_role
from consoleme.lib.ses import (
send_new_comment_notification,
send_policy_request_status_update_v2,
)
from consoleme.models import ExtendedRequestModel, RequestStatus
def escape_json(code):
escaped = re.sub(
r"(?<=</)s(?=cript)", lambda m: f"\\u{ord(m.group(0)):04x}", code, flags=re.I
)
return escaped | null |
162,116 | import base64
import re
import sys
import time
import urllib
from collections import defaultdict
from typing import Dict, List
import ujson as json
from deepdiff import DeepDiff
from policy_sentry.util.actions import get_service_from_action
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
ResourceNotFound,
)
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_service_from_arn,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.role_updater.handler import update_role
from consoleme.lib.ses import (
send_new_comment_notification,
send_policy_request_status_update_v2,
)
from consoleme.models import ExtendedRequestModel, RequestStatus
log = config.get_logger()
stats = get_plugin_by_name(config.get("plugins.metrics", "default_metrics"))()
async def invalid_characters_in_policy(policy_value):
async def parse_policy_change_request(
user: str, arn: str, role: str, data_list: list
) -> dict:
result: dict = {"status": "success"}
function = f"{__name__}.{sys._getframe().f_code.co_name}"
stats.count(function, tags={"user": user, "arn": arn, "role": role})
log_data: dict = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"user": user,
"role": role,
"data_list": data_list,
"arn": arn,
"message": "Incoming request",
}
log.debug(log_data)
events: list = []
for data in data_list:
requester: str = user
# Make sure the requester is only ever 64 chars with domain
if len(requester) > 64:
split_items: list = requester.split("@")
requester: str = (
split_items[0][: (64 - (len(split_items[-1]) + 1))]
+ "@"
+ split_items[-1]
)
event: dict = {
"arn": arn,
"inline_policies": [],
"managed_policies": [],
"requester": requester,
}
if data.get("value") and await invalid_characters_in_policy(data["value"]):
result["status"] = "error"
result["error"] = "Invalid characters were detected in the policy."
log_data["message"] = result["error"]
log.error(log_data)
return result
if data["type"] == "InlinePolicy":
name = data["name"]
value = data.get("value")
if value:
value = json.loads(value)
log_data["message"] = "Update inline policy"
log_data["policy_name"] = name
log_data["policy_value"] = value
log.debug(log_data)
# Check if policy being updated is the same as existing policy.
# Check if a new policy is being created, ensure that we don't overwrite another policy with same name
for existing_policy in role["policy"]["RolePolicyList"]:
if data.get("is_new") and existing_policy.get("PolicyName") == name:
result["status"] = "error"
result[
"error"
] = "You cannot make or request a new policy that has the same name as an existing policy."
log_data["message"] = result["error"]
log.error(log_data)
return result
if existing_policy.get("PolicyName") == name:
if existing_policy.get("PolicyDocument") == value:
result["status"] = "error"
result[
"error"
] = "No changes were found between the updated and existing policy."
log_data["message"] = result["error"]
log.error(log_data)
return result
action = data.get("action", "attach")
entry = {"action": action, "policy_name": name}
if value:
entry["policy_document"] = value
event["inline_policies"].append(entry)
events.append(event)
if data["type"] == "ManagedPolicy":
policy_arn = data["arn"]
action = data["action"]
policy_name = data["name"]
log_data["message"] = "Update managed policy"
log_data["action"] = action
log_data["policy_arn"] = policy_arn
log.debug(log_data)
entry: dict = {"action": action, "arn": policy_arn}
if action == "detach":
seen = False
for policy in role["policy"]["AttachedManagedPolicies"]:
if policy["PolicyName"] == policy_name:
seen = True
break
if not seen:
result["status"] = "error"
result["error"] = (
f"There is no policy attached to role {arn} "
f"with arn {policy_arn} that can be removed."
)
log_data["message"] = result["error"]
log.error(log_data)
return result
event["managed_policies"].append(entry)
events.append(event)
elif action == "attach":
for policy in role["policy"]["AttachedManagedPolicies"]:
if policy["PolicyName"] == policy_name:
result["status"] = "error"
result["error"] = (
f"There is already a policy attached to role {arn} "
f"with arn {policy_arn}."
)
log_data["message"] = result["error"]
log.error(log_data)
return result
event["managed_policies"].append(entry)
events.append(event)
elif data["type"] == "AssumeRolePolicyDocument":
action = "update"
value = json.loads(data["value"])
log_data["message"] = "Update AssumeRolePolicyDocument"
log_data["policy_value"] = data["value"]
log.debug(log_data)
# Check if policy being updated is the same as existing policy
if role["policy"].get("AssumeRolePolicyDocument") == value:
result["status"] = "error"
result[
"error"
] = "No changes were found between the updated and existing assume role policy document."
log_data["message"] = result["error"]
log.error(log_data)
return result
# Todo(ccastrapel): Validate AWS syntax
event["assume_role_policy_document"] = {
"action": action,
"assume_role_policy_document": value,
}
events.append(event)
elif data["type"] == "delete_tag":
action = "remove"
key = data["name"]
event["tags"] = [{"action": action, "key": key}]
events.append(event)
elif data["type"] == "update_tag":
action = "add"
key = data["name"]
value = data["value"]
event["tags"] = [{"action": action, "key": key, "value": value}]
events.append(event)
result["events"] = events
return result | null |
162,117 | import base64
import re
import sys
import time
import urllib
from collections import defaultdict
from typing import Dict, List
import ujson as json
from deepdiff import DeepDiff
from policy_sentry.util.actions import get_service_from_action
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
ResourceNotFound,
)
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_service_from_arn,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.role_updater.handler import update_role
from consoleme.lib.ses import (
send_new_comment_notification,
send_policy_request_status_update_v2,
)
from consoleme.models import ExtendedRequestModel, RequestStatus
def can_admin_policies(user: str, user_groups: List[str]) -> bool:
if can_admin_all(user, user_groups):
return True
if is_in_group(
user,
user_groups,
[
*config.get("groups.can_admin_policies", []),
*config.get("dynamic_config.groups.can_admin_policies", []),
],
):
return True
return False
async def can_update_requests(request, user, groups):
# Users can update their own requests
can_update = user in request["username"]
# Allow admins to return requests back to pending state
if not can_update:
if can_admin_policies(user, groups):
return True
return can_update | null |
162,118 | import base64
import re
import sys
import time
import urllib
from collections import defaultdict
from typing import Dict, List
import ujson as json
from deepdiff import DeepDiff
from policy_sentry.util.actions import get_service_from_action
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
ResourceNotFound,
)
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_service_from_arn,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.role_updater.handler import update_role
from consoleme.lib.ses import (
send_new_comment_notification,
send_policy_request_status_update_v2,
)
from consoleme.models import ExtendedRequestModel, RequestStatus
log = config.get_logger()
stats = get_plugin_by_name(config.get("plugins.metrics", "default_metrics"))()
async def update_role(event):
log_data = {
"function": f"{__name__}.{sys._getframe().f_code.co_name}",
"event": event,
"message": "Working on event",
}
log.debug(log_data)
if not isinstance(event, list):
raise Exception("The passed event must be a list.")
# Let's normalize all of the policies to JSON if they are not already
for d in event:
for i in d.get("inline_policies", []):
if i.get("policy_document") and isinstance(i.get("policy_document"), dict):
i["policy_document"] = json.dumps(
i["policy_document"], escape_forward_slashes=False
)
if d.get("assume_role_policy_document", {}):
if isinstance(
d.get("assume_role_policy_document", {}).get(
"assume_role_policy_document"
),
dict,
):
d["assume_role_policy_document"][
"assume_role_policy_document"
] = json.dumps(
d["assume_role_policy_document"]["assume_role_policy_document"],
escape_forward_slashes=False,
)
bad_validation = RoleUpdaterRequest().validate(event, many=True)
if bad_validation:
log_data["error"] = bad_validation
log.error(log_data)
return {"error_msg": "invalid schema passed", "detail_error": bad_validation}
event = RoleUpdaterRequest().load(event, many=True)
result = {"success": False}
for d in event:
arn = d["arn"]
aws_session_name = sanitize_session_name("roleupdater-" + d["requester"])
account_number = await parse_account_id_from_arn(arn)
role_name = await parse_role_name_from_arn(arn)
# TODO: Make configurable
client = boto3_cached_conn(
"iam",
account_number=account_number,
assume_role=config.get("policies.role_name", "ConsoleMe"),
session_name=aws_session_name,
retry_max_attempts=2,
client_kwargs=config.get("boto3.client_kwargs", {}),
)
inline_policies = d.get("inline_policies", [])
managed_policies = d.get("managed_policies", [])
assume_role_doc = d.get("assume_role_policy_document", {})
tags = d.get("tags", [])
if (
not inline_policies
and not managed_policies
and not assume_role_doc
and not tags
):
result["message"] = f"Invalid request. No response taken on event: {event}"
return result
try:
for policy in inline_policies:
await update_inline_policy(client, role_name, policy)
for policy in managed_policies:
await update_managed_policy(client, role_name, policy)
if assume_role_doc:
await update_assume_role_document(client, role_name, assume_role_doc)
for tag in tags:
await update_tags(client, role_name, tag)
except ClientError as ce:
result["message"] = ce.response["Error"]
result["Traceback"] = traceback.format_exc()
return result
result["success"] = True
return result
async def update_role_policy(events):
result = {"status": "success"}
function = f"{__name__}.{sys._getframe().f_code.co_name}"
stats.count(function)
log_data = {"function": function, "message": "Updating role policy"}
response = await update_role(events)
log_data["message"] = "Received Response"
log_data["response"] = response
log.debug(log_data)
if not response.get("success"):
log_data["message"] = "Error"
log_data["error"] = response.get("message")
log.error(log_data)
result["status"] = "error"
result["error"] = log_data["error"]
return result
return result | null |
162,119 | import base64
import re
import sys
import time
import urllib
from collections import defaultdict
from typing import Dict, List
import ujson as json
from deepdiff import DeepDiff
from policy_sentry.util.actions import get_service_from_action
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
ResourceNotFound,
)
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_service_from_arn,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.role_updater.handler import update_role
from consoleme.lib.ses import (
send_new_comment_notification,
send_policy_request_status_update_v2,
)
from consoleme.models import ExtendedRequestModel, RequestStatus
async def get_policy_request_uri(request):
return f"{config.get('url')}/policies/request/{request['request_id']}" | null |
162,120 | import base64
import re
import sys
import time
import urllib
from collections import defaultdict
from typing import Dict, List
import ujson as json
from deepdiff import DeepDiff
from policy_sentry.util.actions import get_service_from_action
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
ResourceNotFound,
)
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_service_from_arn,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.role_updater.handler import update_role
from consoleme.lib.ses import (
send_new_comment_notification,
send_policy_request_status_update_v2,
)
from consoleme.models import ExtendedRequestModel, RequestStatus
def get_actions_for_resource(resource_arn: str, statement: Dict) -> List[str]:
"""For the given resource and policy statement, return the actions that are
for that resource's service.
"""
results: List[str] = []
# Get service from resource
resource_service = get_service_from_arn(resource_arn)
# Get relevant actions from policy doc
actions = statement.get("Action", [])
actions = actions if isinstance(actions, list) else [actions]
for action in actions:
if action == "*":
results.append(action)
else:
if get_service_from_action(action) == resource_service:
if action not in results:
results.append(action)
return results
async def get_resource_account(arn: str) -> str:
"""Return the AWS account ID that owns a resource.
In most cases, this will pull the ID directly from the ARN.
If we are unsuccessful in pulling the account from ARN, we try to grab it from our resources cache
"""
red = await RedisHandler().redis()
resource_account: str = get_account_from_arn(arn)
if resource_account:
return resource_account
resources_from_aws_config_redis_key: str = config.get(
"aws_config_cache.redis_key", "AWSCONFIG_RESOURCE_CACHE"
)
if not red.exists(resources_from_aws_config_redis_key):
# This will force a refresh of our redis cache if the data exists in S3
await retrieve_json_data_from_redis_or_s3(
redis_key=resources_from_aws_config_redis_key,
s3_bucket=config.get("aws_config_cache_combined.s3.bucket"),
s3_key=config.get(
"aws_config_cache_combined.s3.file",
"aws_config_cache_combined/aws_config_resource_cache_combined_v1.json.gz",
),
redis_data_type="hash",
)
resource_info = await redis_hget(resources_from_aws_config_redis_key, arn)
if resource_info:
return json.loads(resource_info).get("accountId", "")
elif "arn:aws:s3:::" in arn:
# Try to retrieve S3 bucket information from S3 cache. This is inefficient and we should ideally have
# retrieved this info from our AWS Config cache, but we've encountered problems with AWS Config historically
# that have necessitated this code.
s3_cache = await retrieve_json_data_from_redis_or_s3(
redis_key=config.get("redis.s3_buckets_key", "S3_BUCKETS"),
redis_data_type="hash",
)
search_bucket_name = arn.split(":")[-1]
for bucket_account_id, buckets in s3_cache.items():
buckets_j = json.loads(buckets)
if search_bucket_name in buckets_j:
return bucket_account_id
return ""
def get_region_from_arn(arn):
"""Given an ARN, return the region in the ARN, if it is available. In certain cases like S3 it is not"""
result = parse_arn(arn)
# Support S3 buckets with no values under region
if result["region"] is None:
result = ""
else:
result = result["region"]
return result
def get_resource_from_arn(arn):
"""Given an ARN, parse it according to ARN namespacing and return the resource. See
http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html for more details on ARN namespacing.
"""
result = parse_arn(arn)
return result["resource"]
def get_service_from_arn(arn):
"""Given an ARN string, return the service"""
result = parse_arn(arn)
return result["service"]
The provided code snippet includes necessary dependencies for implementing the `get_resources_from_events` function. Write a Python function `async def get_resources_from_events(policy_changes: List[Dict]) -> Dict[str, dict]` to solve the following problem:
Returns a dict of resources affected by a list of policy changes along with the actions and other data points that are relevant to them. Returned dict format: { "resource_name": { "actions": ["service1:action1", "service2:action2"], "arns": ["arn:aws:service1:::resource_name", "arn:aws:service1:::resource_name/*"], "account": "1234567890", "type": "service1", "region": "", } }
Here is the function:
async def get_resources_from_events(policy_changes: List[Dict]) -> Dict[str, dict]:
"""Returns a dict of resources affected by a list of policy changes along with
the actions and other data points that are relevant to them.
Returned dict format:
{
"resource_name": {
"actions": ["service1:action1", "service2:action2"],
"arns": ["arn:aws:service1:::resource_name", "arn:aws:service1:::resource_name/*"],
"account": "1234567890",
"type": "service1",
"region": "",
}
}
"""
def default_resource():
return {"actions": [], "arns": [], "account": "", "type": "", "region": ""}
resource_actions: Dict[str, Dict] = defaultdict(default_resource)
for event in policy_changes:
for policy_type in ["inline_policies", "managed_policies"]:
for policy in event.get(policy_type, []):
policy_document = policy["policy_document"]
for statement in policy_document.get("Statement", []):
resources = statement.get("Resource", [])
resources = (
resources if isinstance(resources, list) else [resources]
)
for resource in resources:
if resource == "*":
continue
resource_name = get_resource_from_arn(resource)
if resource_name == "*":
continue
if not resource_actions[resource_name]["account"]:
resource_actions[resource_name][
"account"
] = await get_resource_account(resource)
if not resource_actions[resource_name]["type"]:
resource_actions[resource_name][
"type"
] = get_service_from_arn(resource)
if not resource_actions[resource_name]["region"]:
resource_actions[resource_name][
"region"
] = get_region_from_arn(resource)
resource_actions[resource_name]["arns"].append(resource)
actions = get_actions_for_resource(resource, statement)
resource_actions[resource_name]["actions"].extend(
x
for x in actions
if x not in resource_actions[resource_name]["actions"]
)
return dict(resource_actions) | Returns a dict of resources affected by a list of policy changes along with the actions and other data points that are relevant to them. Returned dict format: { "resource_name": { "actions": ["service1:action1", "service2:action2"], "arns": ["arn:aws:service1:::resource_name", "arn:aws:service1:::resource_name/*"], "account": "1234567890", "type": "service1", "region": "", } } |
162,121 | import base64
import re
import sys
import time
import urllib
from collections import defaultdict
from typing import Dict, List
import ujson as json
from deepdiff import DeepDiff
from policy_sentry.util.actions import get_service_from_action
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
ResourceNotFound,
)
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_service_from_arn,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.role_updater.handler import update_role
from consoleme.lib.ses import (
send_new_comment_notification,
send_policy_request_status_update_v2,
)
from consoleme.models import ExtendedRequestModel, RequestStatus
async def validate_policy_name(policy_name):
class InvalidRequestParameter(BaseException):
def __init__(self, msg=""):
def get_plugin_by_name(plugin_name: str) -> Any:
async def get_formatted_policy_changes(account_id, arn, request):
aws = get_plugin_by_name(config.get("plugins.aws", "default_aws"))()
existing_role: dict = await aws.fetch_iam_role(account_id, arn, force_refresh=True)
policy_changes: list = json.loads(request.get("policy_changes"))
formatted_policy_changes = []
# Parse request json and figure out how to present to the page
for policy_change in policy_changes:
if not policy_change.get("inline_policies"):
policy_change["inline_policies"] = []
if len(policy_change.get("inline_policies")) > 1:
raise InvalidRequestParameter(
"Only one inline policy change at a time is currently supported."
)
for inline_policy in policy_change.get("inline_policies"):
if policy_change.get("arn") != arn:
raise InvalidRequestParameter(
"Only one role can be changed in a request"
)
policy_name = inline_policy.get("policy_name")
await validate_policy_name(policy_name)
policy_document = inline_policy.get("policy_document")
old_policy = {}
new_policy: bool = False
existing_policy_document = {}
if request.get("status") == "approved":
old_policy = request.get("old_policy", {})
if old_policy:
existing_policy_document = json.loads(old_policy)[0]
if not old_policy:
existing_inline_policies = existing_role["policy"].get(
"RolePolicyList", []
)
existing_policy_document = {}
for existing_policy in existing_inline_policies:
if existing_policy["PolicyName"] == policy_name:
existing_policy_document = existing_policy["PolicyDocument"]
# Generate dictionary with old / new policy documents
diff = DeepDiff(existing_policy_document, policy_document)
if not existing_policy_document:
new_policy = True
formatted_policy_changes.append(
{
"name": policy_name,
"old": existing_policy_document,
"new": policy_document,
"diff": diff,
"new_policy": new_policy,
}
)
assume_role_policy_document = policy_change.get("assume_role_policy_document")
if assume_role_policy_document:
if policy_change.get("arn") != arn:
raise InvalidRequestParameter(
"Only one role can be changed in a request"
)
existing_ar_policy = existing_role["policy"]["AssumeRolePolicyDocument"]
old_policy = request.get("old_policy", {})
if old_policy:
existing_ar_policy = json.loads(old_policy)[0]
diff = DeepDiff(
existing_ar_policy,
assume_role_policy_document.get("assume_role_policy_document"),
)
formatted_policy_changes.append(
{
"name": "AssumeRolePolicyDocument",
"old": existing_ar_policy,
"new": assume_role_policy_document.get(
"assume_role_policy_document"
),
"new_policy": False,
"diff": diff,
}
)
resource_policy_documents = request.get("resource_policies")
if resource_policy_documents:
for resource in resource_policy_documents:
existing_policy_document = None
# TODO: make this actually fetch the resource policy
# existing_policy_document = aws.fetch_resource_policy()
new_policy_document = resource["policy_document"]
diff = DeepDiff(existing_policy_document, new_policy_document)
formatted_policy_changes.append(
{
"name": "ResourcePolicy",
"old": existing_policy_document,
"new": new_policy_document,
"new_policy": not existing_policy_document,
"diff": diff,
}
)
return {"changes": formatted_policy_changes, "role": existing_role} | null |
162,122 | import base64
import re
import sys
import time
import urllib
from collections import defaultdict
from typing import Dict, List
import ujson as json
from deepdiff import DeepDiff
from policy_sentry.util.actions import get_service_from_action
from consoleme.config import config
from consoleme.exceptions.exceptions import (
InvalidRequestParameter,
MissingConfigurationValue,
ResourceNotFound,
)
from consoleme.lib.auth import can_admin_policies
from consoleme.lib.aws import (
get_region_from_arn,
get_resource_account,
get_resource_from_arn,
get_service_from_arn,
)
from consoleme.lib.plugins import get_plugin_by_name
from consoleme.lib.role_updater.handler import update_role
from consoleme.lib.ses import (
send_new_comment_notification,
send_policy_request_status_update_v2,
)
from consoleme.models import ExtendedRequestModel, RequestStatus
def get_plugin_by_name(plugin_name: str) -> Any:
if global_plugins.get(plugin_name):
return global_plugins[plugin_name]
plugins = []
for ep in pkg_resources.iter_entry_points("consoleme.plugins"):
plugins.append(ep.name)
if ep.name == plugin_name:
global_plugins[ep.name] = ep.load()
return global_plugins[ep.name]
initial_exception_message = f"Could not find the specified plugin: {plugin_name}. "
if plugin_name == "default_config":
initial_exception_message = (
f"Could not find the specified plugin: {plugin_name}. "
"Please install it with `pip install -e consoleme/default_plugins` "
"from the ConsoleMe base directory. "
)
exception_message = (
initial_exception_message + f"Plugins found: {', '.join(plugins)}. "
f"Make sure you've set the environment variable CONSOLEME_CONFIG_ENTRYPOINT to the name of your configuration "
f"entrypoint, otherwise it will default to `default_config`."
)
raise Exception(exception_message)
class ExtendedRequestModel(RequestModel):
changes: ChangeModelArray
requester_info: UserModel
reviewer: Optional[str] = None
comments: Optional[List[CommentModel]] = None
The provided code snippet includes necessary dependencies for implementing the `should_auto_approve_policy_v2` function. Write a Python function `async def should_auto_approve_policy_v2( extended_request: ExtendedRequestModel, user, user_groups )` to solve the following problem:
This uses your fancy internal logic to determine if a request should be auto-approved or not. The default plugin set included in ConsoleMe OSS will return False.
Here is the function:
async def should_auto_approve_policy_v2(
extended_request: ExtendedRequestModel, user, user_groups
):
"""
This uses your fancy internal logic to determine if a request should be auto-approved or not. The default plugin
set included in ConsoleMe OSS will return False.
"""
aws = get_plugin_by_name(config.get("plugins.aws", "default_aws"))()
return await aws.should_auto_approve_policy_v2(extended_request, user, user_groups) | This uses your fancy internal logic to determine if a request should be auto-approved or not. The default plugin set included in ConsoleMe OSS will return False. |
162,123 | import base64
import json
import sys
import jwt
import requests
import tornado.httpclient
from jwt.algorithms import ECAlgorithm, RSAAlgorithm
from jwt.exceptions import (
ExpiredSignatureError,
ImmatureSignatureError,
InvalidAudienceError,
InvalidIssuedAtError,
InvalidIssuerError,
)
from okta_jwt.utils import verify_exp, verify_iat
from consoleme.config import config
from consoleme.exceptions.exceptions import (
MissingConfigurationValue,
UnableToAuthenticate,
)
log = config.get_logger()
async def populate_oidc_config():
http_client = tornado.httpclient.AsyncHTTPClient()
metadata_url = config.get(
"get_user_by_aws_alb_auth_settings.access_token_validation.metadata_url"
)
if metadata_url:
res = await http_client.fetch(
metadata_url,
method="GET",
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
},
)
oidc_config = json.loads(res.body)
else:
jwks_uri = config.get(
"get_user_by_aws_alb_auth_settings.access_token_validation.jwks_uri"
)
if not jwks_uri:
raise MissingConfigurationValue("Missing OIDC Configuration.")
oidc_config = {
"jwks_uri": jwks_uri,
}
# Fetch jwks_uri for jwt validation
res = await http_client.fetch(
oidc_config["jwks_uri"],
method="GET",
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
},
)
oidc_config["jwks_data"] = json.loads(res.body)
oidc_config["jwt_keys"] = {}
for k in oidc_config["jwks_data"]["keys"]:
key_type = k["kty"]
key_id = k["kid"]
if key_type == "RSA":
oidc_config["jwt_keys"][key_id] = RSAAlgorithm.from_jwk(json.dumps(k))
elif key_type == "EC":
oidc_config["jwt_keys"][key_id] = ECAlgorithm.from_jwk(json.dumps(k))
oidc_config["aud"] = config.get(
"get_user_by_aws_alb_auth_settings.access_token_validation.client_id"
)
return oidc_config
import jwt
class UnableToAuthenticate(BaseException):
"""Unable to authenticate user or app"""
def __init__(self, msg=""):
stats.count("UnableToAuthenticate")
super().__init__(msg)
async def authenticate_user_by_alb_auth(request):
aws_alb_auth_header_name = config.get(
"get_user_by_aws_alb_auth_settings.aws_alb_auth_header_name", "X-Amzn-Oidc-Data"
)
aws_alb_claims_header_name = config.get(
"get_user_by_aws_alb_auth_settings.aws_alb_claims_header_name",
"X-Amzn-Oidc-Accesstoken",
)
function = f"{__name__}.{sys._getframe().f_code.co_name}"
log_data = {"function": function}
encoded_auth_jwt = request.request.headers.get(aws_alb_auth_header_name)
access_token = request.request.headers.get(aws_alb_claims_header_name)
if not encoded_auth_jwt:
raise Exception(f"Missing header: {aws_alb_auth_header_name}")
if not access_token:
raise Exception(f"Missing header: {aws_alb_claims_header_name}")
jwt_headers = encoded_auth_jwt.split(".")[0]
decoded_jwt_headers = base64.b64decode(jwt_headers)
decoded_jwt_headers = decoded_jwt_headers.decode("utf-8")
decoded_json = json.loads(decoded_jwt_headers)
kid = decoded_json["kid"]
# Step 2: Get the public key from regional endpoint
url = "https://public-keys.auth.elb." + config.region + ".amazonaws.com/" + kid
req = requests.get(url)
pub_key = req.text
# Step 3: Get the payload
payload = jwt.decode(encoded_auth_jwt, pub_key, algorithms=["ES256"])
email = payload.get(
config.get("get_user_by_aws_alb_auth_settings.jwt_email_key", "email")
)
if not email:
raise UnableToAuthenticate("Unable to determine user from ID Token")
# Step 4: Parse the Access Token
# User has already passed ALB auth and successfully authenticated
access_token_pub_key = None
jwt_verify = config.get("get_user_by_aws_alb_auth_settings.jwt_verify", True)
access_token_verify_options = {"verify_signature": jwt_verify}
oidc_config = {}
algorithm = None
try:
if jwt_verify:
oidc_config = await populate_oidc_config()
header = jwt.get_unverified_header(access_token)
key_id = header["kid"]
algorithm = header["alg"]
if algorithm == "none" or not algorithm:
raise UnableToAuthenticate(
"Access Token header does not specify a signing algorithm."
)
access_token_pub_key = oidc_config["jwt_keys"][key_id]
decoded_access_token = jwt.decode(
access_token,
access_token_pub_key,
algorithms=[algorithm],
options=access_token_verify_options,
audience=oidc_config.get("aud"),
issuer=oidc_config.get("issuer"),
)
# Step 5: Verify the access token.
if not jwt_verify:
verify_exp(access_token)
verify_iat(access_token)
# Extract groups from tokens, checking both because IdPs aren't consistent here
for token in [decoded_access_token, payload]:
groups = token.get(
config.get("get_user_by_aws_alb_auth_settings.jwt_groups_key", "groups")
)
if groups:
break
except jwt.exceptions.DecodeError as e:
# This exception occurs when the access token is not JWT-parsable. It is expected with some IdPs.
log.debug(
{
**log_data,
"message": (
"Unable to decode claims token. This is expected for some Identity Providers."
),
"error": e,
"user": email,
}
)
log.debug(log_data, exc_info=True)
groups = []
except (
ExpiredSignatureError,
ImmatureSignatureError,
InvalidAudienceError,
InvalidIssuedAtError,
InvalidIssuerError,
) as e:
# JWT Validation failed, log an error and revoke the ALB auth cookie
log.debug(
{
**log_data,
"message": (str(e)),
"error": e,
"user": email,
}
)
log.debug(log_data, exc_info=True)
request.clear_cookie("AWSELBAuthSessionCookie-0")
request.redirect(request.request.uri)
groups = []
return {"user": email, "groups": groups} | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.