def doCleanup(event, context, version): try: ep = EnvParam() spath = ep.getParam("SECRETPATH", True) environment = ep.getParam("environment", True) if spath is not False: pms = Permissions(spath, missing=True) dryrun = True if environment == "dev" else False tfr, afr = pms.cleanKeyMap(dryrun=dryrun) kmsg = "key" if afr == 1 else "keys" kmsg += " would be" if environment == "dev" else "" msg = "chaim cleanup v{}: {}/{} {} cleaned.".format( version, afr, tfr, kmsg) log.info(msg) incMetric("cleanup") ggMetric("cleanup.cleaned", afr) ggMetric("cleanup.existing", tfr) else: emsg = "chaim cleanup: secret path not in environment" log.error(emsg) incMetric("cleanup.error") except Exception as e: emsg = "chaim cleanup v{}: error: {}: {}".format( version, type(e).__name__, e) log.error(emsg) incMetric("cleanup.error")
def slackreq(): """ This is the entry point for Slack """ try: log.debug("slackreq entry") with open("version", "r") as vfn: version = vfn.read() config = {} ep = EnvParam() config["environment"] = ep.getParam("environment") config["useragent"] = "slack" config["apiid"] = app.current_request.context["apiId"] rbody = chaim.begin(app.current_request.raw_body.decode(), **config) chaim.snsPublish(ep.getParam("SNSTOPIC"), rbody) verstr = "chaim-slack" if config["environment"] == "prod": verstr += " " + version else: verstr += "-" + config["environment"] + " " + version return chaim.output(None, "{}\n\nPlease wait".format(verstr)) except Exception as e: emsg = "slackreq: {}: {}".format(type(e).__name__, e) log.error(emsg) return chaim.output(emsg)
def identify(): """ the entry point to display the users identity from slack """ try: log.debug("identify entry") with open("version", "r") as vfn: version = vfn.read() config = {} ep = EnvParam() config["environment"] = ep.getParam("environment") config["useragent"] = "slack" config["apiid"] = app.current_request.context["apiId"] log.debug("identify: config: {}".format(config)) params = chaim.paramsToDict(app.current_request.raw_body.decode()) # rbody = chaim.begin(app.current_request.raw_body.decode(), **config) op = "```\n" op += "Name: {}\n".format(params["user_name"]) op += "Slack Id: {}\n".format(params["user_id"]) op += "Workspace Id: {}\n".format(params["team_id"]) op += "```\n" # rbody = glue.addToReqBody(rbody, "identify", "true") # log.debug("publishing req body: {}".format(rbody)) # chaim.snsPublish(ep.getParam("SNSTOPIC"), rbody) verstr = "chaim-slack-" + config["environment"] + " " + version log.debug("identify: {}".format(op)) return chaim.output(None, "{}\n\n{}".format(verstr, op)) except Exception as e: msg = "An identify error occurred: {}: {}".format(type(e).__name__, e) log.error(msg) return chaim.output(msg)
def doStart(reqbody, context, env, version): try: verstr = "chaim-cli-{}".format(env) + " " + version log.debug("{} doStart entered: {}".format(verstr, reqbody)) ep = EnvParam() secretpath = ep.getParam("SECRETPATH") pms = Permissions(secretpath, stagepath=env + "/") cp = CommandParse(reqbody, roledict=pms.roleAliasDict()) emsg = "" if cp.dolist: log.debug("cli account list request") kdict = {"accountlist": pms.accountList()} else: rdict = cp.requestDict() msg = "incoming CLI request: user agent" msg += " unknown!" if rdict["useragent"] is None else " {}".format( rdict["useragent"]) log.info(msg) if "role" in rdict: if rdict["role"] is None: raise DataNotFound("Role not recognised: {}".format( rdict["rolealias"])) log.debug("incoming cli request: {}".format(rdict)) kdict, rdict = chaim.buildCredentials(pms, rdict, noUrl=True) if kdict is None: emsg = "Failed to build credentials" else: chaim.incMetric("key.cli") return [emsg, kdict] except Exception as e: emsg = "doStart: Error {}: {}".format(type(e).__name__, e) log.error(emsg) chaim.incMetric("key.cli.error") return [emsg, None]
def snsreq(event, context): """This is the entry point for the SNS chaim handler :param event: the AWS lambda event that triggered this :param context: the AWS lambda context for this """ log.info("context: {}".format(context)) ep = EnvParam() environment = ep.getParam("environment", True) apiid = ep.getParam("APIID", True) with open("version", "r") as vfn: version = vfn.read() body = event['Records'][0]['Sns']['Message'] rbody = chaim.begin(body, environment, "slack", apiid) verstr = "chaim-snsreq-" + environment + " " + version log.info(verstr + " entered.") log.debug("sns req: {}".format(rbody)) doSnsReq(rbody, context, verstr, ep, environment)
def keyinit(): """ the entry point to request a user key (from slack /initchaim) """ try: with open("version", "r") as vfn: version = vfn.read() config = {} ep = EnvParam() config["environment"] = ep.getParam("environment") config["useragent"] = "slack" config["apiid"] = app.current_request.context["apiId"] rbody = chaim.begin(app.current_request.raw_body.decode(), **config) rbody = glue.addToReqBody(rbody, "keyinit", "true") chaim.snsPublish(ep.getParam("SNSTOPIC"), rbody) verstr = "chaim-slack-" + config["environment"] + " " + version return chaim.output(None, "{}\n\nPlease wait".format(verstr)) # reqbody = app.current_request.raw_body.decode() # reqbody += "&stage=" # stage = app.current_request.context["stage"] # apiid = app.current_request.context["apiId"] # useragent = "slack" # if stage == "dev": # log.setLevel(logging.DEBUG) # reqbody += stage # reqbody += "&apiid={}&keyinit=true".format(apiid) # reqbody += "&useragent={}".format(useragent) # log.debug("keyinit starting: {}".format(reqbody)) # log.debug("sending to sns: {}".format(reqbody)) # epm = EnvParam() # snstopicarn = epm.getParam("SNSTOPIC", decode=True) # snsc = boto3.client('sns') # snsc.publish(TopicArn=snstopicarn, Message=reqbody) # extrav = "-{}".format(stage) if stage in ["beta", "dev"] else "" # return output(None, "{}\n\nPlease wait".format(verstr + extrav)) except Exception as e: msg = "A keyinit error occurred: {}: {}".format(type(e).__name__, e) log.error(msg) return output(msg)
def keyinit(): """ the entry point to request a user key (from slack /initchaim) """ try: log.debug("keyinit entry") with open("version", "r") as vfn: version = vfn.read() config = {} ep = EnvParam() config["environment"] = ep.getParam("environment") config["useragent"] = "slack" config["apiid"] = app.current_request.context["apiId"] rbody = chaim.begin(app.current_request.raw_body.decode(), **config) rbody = glue.addToReqBody(rbody, "keyinit", "true") chaim.snsPublish(ep.getParam("SNSTOPIC"), rbody) verstr = "chaim-slack-" + config["environment"] + " " + version return chaim.output(None, "{}\n\nPlease wait".format(verstr)) except Exception as e: msg = "A keyinit error occurred: {}: {}".format(type(e).__name__, e) log.error(msg) return chaim.output(msg)
def rotate(event, context): try: ep = EnvParam() env = ep.getParam("environment") if env in ["dev", "test"]: glue.setDebug() enckeyname = ep.getParam("KEYNAME") iamusername = ep.getParam("CHAIMUSER") log.info("Rotating access key for {}".format(iamusername)) log.debug("enckeyname: {}".format(enckeyname)) log.debug("iamusername: {}".format(iamusername)) iam = IamClient(iamusername) user = iam.getKeys() if user is False: log.debug("getkeys is false, yet: {}".format(iam.user["keys"])) key = iam.rotateKeys() if isinstance(key, dict) and "AccessKey" in key: log.debug("new key: {}".format(key)) accesskeyid = key["AccessKey"]["AccessKeyId"] secretkeyid = key["AccessKey"]["SecretAccessKey"] ps = ParamStore() ret = ps.putEStringParam("/sre/chaim/accesskeyid", accesskeyid, "alias/" + enckeyname) if ret is None: raise AccessKeyError( "Failed to store encrypted parameter 'accesskeyid'") log.debug("storing key ret: {}".format(ret)) ret = ps.putEStringParam("/sre/chaim/secretkeyid", secretkeyid, "alias/" + enckeyname) if ret is None: raise AccessKeyError( "Failed to store encrypted parameter 'secretkeyid'") log.debug("storing secret ret: {}".format(ret)) log.info("access key rotated for {}".format(iamusername)) else: emsg = "Rotate failed to generate a new key: {}".format(key) raise (AccessKeyError(emsg)) except Exception as e: log.error("rotate: {}: {}".format(type(e).__name__, e))
def newchaimuser(): """ the entry point to create a new chaim user """ try: log.debug("newchaimuser entry") with open("version", "r") as vfn: version = vfn.read() config = {} ep = EnvParam() config["environment"] = ep.getParam("environment") config["useragent"] = "slack" config["apiid"] = app.current_request.context["apiId"] log.debug("newchaimuser: config: {}".format(config)) # params = chaim.paramsToDict(app.current_request.raw_body.decode()) rbody = chaim.begin(app.current_request.raw_body.decode(), **config) rbody = glue.addToReqBody(rbody, "newchaimuser", "true") chaim.snsPublish(ep.getParam("SNSTOPIC"), rbody) verstr = "chaim-slack-" + config["environment"] + " " + version return chaim.output(None, "{}\n\nPlease wait".format(verstr)) except Exception as e: msg = "An identify error occurred: {}: {}".format(type(e).__name__, e) log.error(msg) return chaim.output(msg)
def startgui(): """ The entry point for the CLI to obtain a gui url """ try: config = {} ep = EnvParam() config["environment"] = ep.getParam("environment") rbody = chaim.begin(app.current_request.raw_body.decode(), **config) with open("version", "r") as vfn: version = vfn.read() emsg, msg = doStartGui(rbody, app.lambda_context, config["environment"], version) return chaim.output(emsg, msg) except Exception as e: emsg = "cligui start: {}: {}".format(type(e).__name__, e) log.error(emsg) return chaim.output(emsg)
def cleanup(event, context): """ This is the entry point for the cleanup cron cloudwatch cron expression: 23 4 * * ? * ( 04:23 every day ) :param event: the AWS lambda event that triggered this :param context: the AWS lambda context for this """ with open("version", "r") as vfn: version = vfn.read() ep = EnvParam() environment = ep.getParam("environment", True) if "dev" == environment: glue.setDebug() log.info("chaim cleanup v{}: entered".format(version)) log.info("environment: {}".format(environment)) getWFKey(stage=environment) doCleanup(event, context, version)
def getWFKey(stage="prod"): """ retrieves the wavefront access key from the param store and populates the environment with it """ try: ep = EnvParam() secretpath = ep.getParam("SECRETPATH", decode=True) pms = Permissions(secretpath, stagepath=stage + "/", missing=False, quick=True) wfk = pms.getEncKey("wavefronttoken") os.environ["WAVEFRONT_API_TOKEN"] = wfk os.environ["CHAIM_STAGE"] = stage log.debug("getWFKey: stage: {}".format(os.environ["CHAIM_STAGE"])) except Exception as e: msg = "getWFKey error occurred: {}: {}".format(type(e).__name__, e) log.error(msg) raise
def test_getWFKey(): getWFKey("dev") ep = EnvParam() wft = ep.getParam("WAVEFRONT_API_TOKEN", True) assert wft is not False