Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ SERVICE_TAG=${tag}
AWS_REGION=us-west-2
ECR=${AWS_ACCT}.dkr.ecr.us-west-2.amazonaws.com
ECS_API_REPO=${ECR}/${API}
INTERNAL_REPO=${ECR}/internal

all: build push deploy

Expand All @@ -24,4 +25,16 @@ push: test-envvars
docker push $(ECS_API_REPO):${SERVICE_TAG}

deploy: test-envvars
aws ecs --region $(AWS_REGION) update-service --cluster $(ECS_CLUSTER) --service ${API} --force-new-deployment
aws ecs --region $(AWS_REGION) update-service --cluster $(ECS_CLUSTER) --service ${API} --force-new-deployment

build-internal:test-envvars
GOOS=linux GOARCH=amd64 go build -o ./cmd/internal/main ./cmd/internal/main.go
docker build --platform linux/amd64 -t $(INTERNAL_REPO):${SERVICE_TAG} cmd/internal/
rm cmd/internal/main

push-internal:test-envvars
aws ecr get-login-password --region $(AWS_REGION) | docker login --username AWS --password-stdin $(INTERNAL_REPO)
docker push $(INTERNAL_REPO):${SERVICE_TAG}

deploy-internal: test-envvars
aws ecs --region $(AWS_REGION) update-service --cluster internal --service internal --force-new-deployment
18 changes: 17 additions & 1 deletion api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,22 @@ func Start(config APIConfig) {
baseMiddleware(config.Logger, e)
e.GET("/heartbeat", heartbeat)
authService := authRoute(config, e)
platformRoute(config, e)
AuthAPIKey(config, e, true)
transactRoute(config, authService, e)
userRoute(config, authService, e)
verificationRoute(config, e)
e.Logger.Fatal(e.Start(":" + config.Port))
}

func StartInternal(config APIConfig) {
e := echo.New()
baseMiddleware(config.Logger, e)
e.GET("/heartbeat", heartbeat)
platformRoute(config, e)
AuthAPIKey(config, e, true)
e.Logger.Fatal(e.Start(":" + config.Port))
}

func baseMiddleware(logger *zerolog.Logger, e *echo.Echo) {
e.Use(middleware.CORS())
e.Use(middleware.RequestID())
Expand Down Expand Up @@ -64,6 +73,13 @@ func platformRoute(config APIConfig, e *echo.Echo) {
handler.RegisterRoutes(e.Group("/platform"), middleware.BearerAuth())
}

func AuthAPIKey(config APIConfig, e *echo.Echo, internal bool) {
a := repository.NewAuth(config.Redis, config.DB)
service := service.NewAPIKeyStrategy(a)
handler := handler.NewAuthAPIKey(service, internal)
handler.RegisterRoutes(e.Group("/apikey"))
}

func transactRoute(config APIConfig, auth service.Auth, e *echo.Echo) {
repos := service.TransactionRepos{
Asset: repository.NewAsset(config.DB),
Expand Down
91 changes: 91 additions & 0 deletions api/handler/auth_key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package handler

import (
"net/http"

"github.com/String-xyz/string-api/pkg/service"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
)

type AuthAPIKey interface {
Create(c echo.Context) error
Approve(c echo.Context) error
List(c echo.Context) error
RegisterRoutes(g *echo.Group, ms ...echo.MiddlewareFunc)
}

type authAPIKey struct {
isInternal bool
service service.APIKeyStrategy
logger *zerolog.Logger
}

func NewAuthAPIKey(service service.APIKeyStrategy, internal bool) AuthAPIKey {
return &authAPIKey{service: service, isInternal: internal}
}

func (o authAPIKey) Create(c echo.Context) error {
lg := c.Get("logger").(*zerolog.Logger)
key, err := o.service.Create()
if err != nil {
lg.Err(err).Stack().Msg("authKey approve:create")
return echo.NewHTTPError(http.StatusInternalServerError, "Unable to process request")
}
return c.JSON(http.StatusOK, map[string]string{"apiKey": key})
}

func (o authAPIKey) List(c echo.Context) error {
if !o.isInternal {
return c.String(http.StatusMethodNotAllowed, "Not Allowed")
}
lg := c.Get("logger").(*zerolog.Logger)
body := struct {
Status string `query:"status"`
Limit int `query:"limit"`
Offset int `query:"offset"`
}{}
err := c.Bind(&body)
if err != nil {
lg.Err(err).Stack().Msg("authKeys list: bind")
return echo.NewHTTPError(http.StatusBadRequest)
}
list, err := o.service.List(body.Limit, body.Offset, body.Status)
if err != nil {
lg.Err(err).Stack().Msg("authKeys list")
return echo.NewHTTPError(http.StatusInternalServerError, "ApiKey Service Failed")
}
return c.JSON(http.StatusCreated, list)
}

func (o authAPIKey) Approve(c echo.Context) error {
if !o.isInternal {
return c.String(http.StatusMethodNotAllowed, "Not Allowed")
}
lg := c.Get("logger").(*zerolog.Logger)
params := struct {
ID string `param:"id"`
}{}
err := c.Bind(&params)

if err != nil {
lg.Err(err).Stack().Msg("authKey approve:bind")
return echo.NewHTTPError(http.StatusInternalServerError, "Unable to process request")
}
err = o.service.Approve(params.ID)
if err != nil {
lg.Err(err).Stack().Msg("authKey approve:approve")
return echo.NewHTTPError(http.StatusInternalServerError, "Unable to process request")
}
return c.String(http.StatusOK, "Success")
}

func (o authAPIKey) RegisterRoutes(g *echo.Group, ms ...echo.MiddlewareFunc) {
if g == nil {
panic("no group attached to the authKey handler")
}
g.Use(ms...)
g.POST("", o.Create)
g.GET("", o.List)
g.POST("/:id/approve", o.Approve)
}
5 changes: 2 additions & 3 deletions Dockerfile → cmd/app/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ LABEL Description="core string api"

EXPOSE 3000
# Copy over the app files
COPY ./tmp/app .
COPY ./main .


CMD ["./app"]
CMD ["./main"]
11 changes: 11 additions & 0 deletions cmd/internal/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM alpine:3.16.0

LABEL maintainer="Marlon Monroy<marlon@string.xyz>"
LABEL Description="internal string api"

EXPOSE 3000
# Copy over the files
COPY ./main .


CMD ["./main"]
35 changes: 35 additions & 0 deletions cmd/internal/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main

import (
"os"

"github.com/String-xyz/string-api/api"
"github.com/String-xyz/string-api/pkg/store"
"github.com/joho/godotenv"
"github.com/rs/zerolog"
"github.com/rs/zerolog/pkgerrors"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)

func main() {
// load .env file
godotenv.Load(".env") // removed the err since in cloud this wont be loaded
tracer.Start()

defer tracer.Stop()
port := os.Getenv("PORT")
if port == "" {
panic("no port!")
}

zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
db := store.MustNewPG()
lg := zerolog.New(os.Stdout)
// setup api
api.StartInternal(api.APIConfig{
DB: db,
Redis: store.NewRedisStore(),
Port: port,
Logger: &lg,
})
}
22 changes: 22 additions & 0 deletions infra/internal/dev/.terraform.lock.hcl

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions infra/internal/dev/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export
AWS_PROFILE=dev-string

init:
terraform init
plan:
terraform plan
apply:
terraform apply

destroy:
terraform destroy
84 changes: 84 additions & 0 deletions infra/internal/dev/alb.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
module "alb_acm" {
source = "../../acm"
domain_name = "admin.${local.root_domain}"
aws_region = "us-west-2"
zone_id = data.aws_route53_zone.root.zone_id
tags = {
Name = "admin-${local.root_domain}-alb"
}
}

resource "aws_alb" "alb" {
name = "${local.service_name}-alb"
internal = true
drop_invalid_header_fields = true
security_groups = [aws_security_group.ecs_alb_https_sg.id]
subnets = data.terraform_remote_state.vpc.outputs.public_subnets

tags = {
Name = "${local.service_name}-alb"
}

lifecycle {
create_before_destroy = true
}
}

resource "aws_alb_target_group" "ecs_task_target_group" {
name = "${local.service_name}-tg"
port = local.container_port
vpc_id = data.terraform_remote_state.vpc.outputs.id
target_type = "ip"
protocol = "HTTP"

lifecycle {
create_before_destroy = true
}

health_check {
path = "/heartbeat"
protocol = "HTTP"
matcher = "200"
interval = 60
timeout = 30
unhealthy_threshold = "3"
healthy_threshold = "3"
}

tags = {
Name = "${local.service_name}-tg"
}
}

resource "aws_alb_listener" "alb_https_listener" {
load_balancer_arn = aws_alb.alb.arn
port = 443
protocol = "HTTPS"
ssl_policy = "ELBSecurityPolicy-TLS-1-2-2017-01"
certificate_arn = module.alb_acm.arn

lifecycle {
create_before_destroy = true
}

default_action {
type = "forward"
target_group_arn = aws_alb_target_group.ecs_task_target_group.arn
}
}

resource "aws_alb_listener_rule" "ecs_alb_listener_rule" {
listener_arn = aws_alb_listener.alb_https_listener.arn
priority = 100
action {
type = "forward"
target_group_arn = aws_alb_target_group.ecs_task_target_group.arn
}

condition {
host_header {
values = ["admin.${local.root_domain}"]
}
}
}

35 changes: 35 additions & 0 deletions infra/internal/dev/backend.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
locals {
remote_state_bucket = "dev-string-terraform-state"
backend_region = "us-west-2"
vpc_remote_state_key = "vpc.tfstate"
}

provider "aws" {
region = "us-west-2"
}

terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "4.37.0"
}
}

backend "s3" {
encrypt = true
key = "internal.tfstate"
bucket = "dev-string-terraform-state"
dynamodb_table = "dev-string-terraform-state-lock"
region = "us-west-2"
}
}

data "terraform_remote_state" "vpc" {
backend = "s3"
config = {
region = local.backend_region
bucket = local.remote_state_bucket
key = local.vpc_remote_state_key
}
}
14 changes: 14 additions & 0 deletions infra/internal/dev/domain.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
data "aws_route53_zone" "root" {
name = local.root_domain
}

resource "aws_route53_record" "domain" {
name = "admin.${local.root_domain}"
type = "A"
zone_id = data.aws_route53_zone.root.zone_id
alias {
evaluate_target_health = false
name = aws_alb.alb.dns_name
zone_id = aws_alb.alb.zone_id
}
}
Loading