Skip to content

Commit

Permalink
Merge pull request #1 from phuonghuynh/dev
Browse files Browse the repository at this point in the history
Separate Lambda@Edge module
  • Loading branch information
ronaldtse authored Nov 30, 2018
2 parents d0866d6 + 9343ef4 commit 233cb4d
Show file tree
Hide file tree
Showing 6 changed files with 211 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.archive*
.idea/
.iml
38 changes: 38 additions & 0 deletions main.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
resource "template_dir" "this" {
source_dir = "${path.module}/src"
destination_dir = "${path.module}/.archive"

vars {
BUCKET_NAME = "${var.bucket_name}"
BUCKET_KEY = "${var.bucket_key}"

BASIC_USER = "${var.basic_user}"
BASIC_PWD = "${var.basic_password}"
}
}

data "archive_file" "this" {
depends_on = [
"template_dir.this",
]

type = "zip"
output_path = "${path.module}/.archive.zip"
source_dir = "${template_dir.this.destination_dir}"
}

resource "aws_lambda_function" "this" {
description = "Basic HTTP authentication module/function"
role = "${aws_iam_role.this.arn}"
runtime = "nodejs8.10"

filename = "${data.archive_file.this.output_path}"
source_code_hash = "${data.archive_file.this.output_base64sha256}"

function_name = "${var.name}"
handler = "basic_auth.handler"

timeout = "${var.fn_timeout}"
memory_size = "${var.fn_memory_size}"
publish = true
}
23 changes: 23 additions & 0 deletions outputs.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
output "fn_name" {
value = "${aws_lambda_function.this.function_name}"
}

output "arn" {
value = "${aws_lambda_function.this.arn}"
}

output "qualified_arn" {
value = "${aws_lambda_function.this.qualified_arn}"
}

output "invoke_arn" {
value = "${aws_lambda_function.this.invoke_arn}"
}

output "id" {
value = "${aws_lambda_function.this.id}"
}

output "version" {
value = "${aws_lambda_function.this.version}"
}
59 changes: 59 additions & 0 deletions src/basic_auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

//https://medium.com/@yagonobre/automatically-invalidate-cloudfront-cache-for-site-hosted-on-s3-3c7818099868
exports.handler = async (event, context, callback) => {
const request = event.Records[0].cf.request;
const uri = request.uri;

if (!'${BUCKET_NAME}') {
console.log(`Bucket not defined (key is empty) => ignore`);
return callback(null, request);
}

try {
const filesStr = await readRestrictedFiles();
if (!filesStr) {
throw new Error(`empty protect files => ignore`);
}

const rawFiles = JSON.parse(await readRestrictedFiles());
if (!Array.isArray(rawFiles)) {
throw new Error('${BUCKET_KEY} is not any array => ignore')
}
const files = rawFiles.map(f => f.startsWith('/') ? f : '/' + f);
if (!files.includes(uri)) {
throw new Error(uri + ` not protected`);
}

const headers = request.headers;

const authUser = '${BASIC_USER}';
const authPass = '${BASIC_PWD}';

const authString = 'Basic ' + new Buffer(authUser + ':' + authPass).toString('base64');
if (typeof headers.authorization === 'undefined' || headers.authorization[0].value !== authString) {
const body = 'Unauthorized';
const response = {
status: '401',
statusDescription: 'Unauthorized',
body: body,
headers: {
'www-authenticate': [{key: 'WWW-Authenticate', value:'Basic'}]
},
};
return callback(null, response);
}
}
catch(e) {
console.error(e);
}
return callback(null, request);
};

async function readRestrictedFiles() {
const params = { Bucket: '${BUCKET_NAME}', Key: '${BUCKET_KEY}' };
const data = await s3.getObject(params).promise();
return data.Body.toString();
}
64 changes: 64 additions & 0 deletions sts_role.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
data "aws_iam_policy_document" "sts" {
statement {
effect = "Allow"

actions = [
"sts:AssumeRole",
]

principals {
type = "Service"

identifiers = [
"lambda.amazonaws.com",
"edgelambda.amazonaws.com",
]
}
}
}

data "aws_iam_policy_document" "this" {
statement {
effect = "Allow"

actions = [
"s3:GetBucketLocation",
"s3:ListBucket",
"s3:GetObject",
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:DescribeLogGroups",
"logs:DescribeLogStreams",
"logs:PutLogEvents",
"logs:GetLogEvents",
"logs:FilterLogEvents",
]

resources = [
"arn:aws:logs:*:*:*"
]
}

statement {
effect = "Allow"

actions = [
"lambda:GetFunction",
]

resources = [
"${aws_lambda_function.this.arn}:*",
]
}
}

resource "aws_iam_role_policy" "this" {
name = "${var.name}"
role = "${aws_iam_role.this.id}"
policy = "${data.aws_iam_policy_document.this.json}"
}

resource "aws_iam_role" "this" {
name = "${var.name}"
assume_role_policy = "${data.aws_iam_policy_document.sts.json}"
}
24 changes: 24 additions & 0 deletions vars.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
variable "name" {
default = "terraform-aws-lambda-edge-authentication"
}

// Lambda limits https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-limits.html
variable "fn_timeout" {
default = 3
}

variable "fn_memory_size" {
default = 128
}

variable "bucket_name" {
}

variable "bucket_key" {
}

variable "basic_user" {
}

variable "basic_password" {
}

0 comments on commit 233cb4d

Please sign in to comment.