Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement CSRF automatic validation #21

Merged
merged 4 commits into from
Jan 26, 2025
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
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ CAPTCHA_SECRET=
HTTPS_ENABLED=false
HTTPS_CRT=
HTTPS_KEY=

CSRF_ENABLED=true
REDIS_CONNECTION=localhost:6379
2 changes: 0 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ name: build

on:
workflow_dispatch:
release:
types: [ published ]

env:
REGISTRY: docker.io
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ env:
jobs:
deploy:
runs-on: [self-hosted, Linux, x64]
environment: prod
permissions:
contents: read
packages: write
Expand Down
139 changes: 139 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
name: release

on:
workflow_dispatch:
release:
types: [ published ]

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: false

env:
REGISTRY: docker.io
REPO: cashtrack/gateway
INFRA_REPO: cash-track/infra
INFRA_REPO_REF: main
CLUSTER: k8s-cash-track
NAMESPACE: cash-track
KUBECTL_BIN: ${{ vars.KUBECTL_BIN_URL }}

jobs:
build:
runs-on: [self-hosted, Linux, x64]
permissions:
contents: read
packages: write
id-token: write
attestations: write

steps:
- name: Checkout repository
if: github.event_name != 'pull_request'
uses: actions/checkout@v4

# Login against a Docker registry except on PR
# https://github.com/docker/login-action
- name: Login to Docker Hub
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_HUB_USER }}
password: ${{ secrets.DOCKER_HUB_TOKEN }}

# Extract metadata (tags, labels) for Docker
# https://github.com/docker/metadata-action
- name: Extract Docker metadata
if: github.event_name != 'pull_request'
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REPO }}
tags: |
type=sha
type=semver,pattern={{version}}

# Setup BuildX
# https://github.com/docker/setup-buildx-action
- name: Setup BuildX
uses: docker/setup-buildx-action@v3
id: buildx
with:
install: true

# Build and push Docker image with Build (don't push on PR)
# https://github.com/docker/build-push-action
- name: Build and push
uses: docker/build-push-action@v6
id: push
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
GIT_COMMIT=${{ github.sha }}
GIT_TAG=${{ github.ref_name }}

- name: Attest
uses: actions/attest-build-provenance@v1
id: attest
with:
subject-name: ${{ env.REGISTRY }}/${{ env.REPO }}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true

deploy:
runs-on: [self-hosted, Linux, x64]
environment: prod
permissions:
contents: read
packages: write

steps:
- name: Checkout infra repository
uses: actions/checkout@v4
with:
repository: ${{ env.INFRA_REPO }}
ref: ${{ env.INFRA_REPO_REF }}
path: deploy

- name: Install doctl
uses: digitalocean/action-doctl@v2
with:
token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }}

- name: Install kubectl
run: |
curl -LO ${{ env.KUBECTL_BIN }}
chmod +x ./kubectl
sudo mv ./kubectl /usr/local/bin/kubectl

- name: Configure kubectl
run: doctl kubernetes cluster kubeconfig save --expiry-seconds 600 ${{ env.CLUSTER }}

# Extract metadata (tags, labels) for Docker
# https://github.com/docker/metadata-action
- name: Extract Docker metadata
if: github.event_name != 'pull_request'
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REPO }}
tags: |
type=semver,pattern={{version}}

- name: Update deployment
env:
IMAGE: ${{ env.REPO }}:${{ fromJSON(steps.meta.outputs.json).labels['org.opencontainers.image.version'] }}
run: sed -i 's|${{ env.REPO }}:latest|'${IMAGE}'|' $GITHUB_WORKSPACE/deploy/services/gateway/deployment.yml

- name: Update definition
run: kubectl apply -f $GITHUB_WORKSPACE/deploy/services/gateway/

- name: Verify deployment
run: kubectl -n ${{ env.NAMESPACE }} rollout status deployment/gateway

- name: Verify service ready
run: kubectl -n ${{ env.NAMESPACE }} wait pods -l app=gateway --for condition=Ready --timeout=120s

1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,5 @@ mock-gen:
mockgen -source=captcha/provider.go -package=mocks -destination=mocks/captcha_provider_mock.go -mock_names=Provider=CaptchaProviderMock
mockgen -source=service/api/service.go -package=mocks -destination=mocks/api_service_mock.go -mock_names=Service=ApiServiceMock
mockgen -source=router/api/handler.go -package=mocks -destination=mocks/api_handler_mock.go -mock_names=Handler=ApiHandlerMock
mockgen -source=router/csrf/handler.go -package=mocks -destination=mocks/csrf_handler_mock.go -mock_names=Handler=CsrfHandlerMock

6 changes: 6 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ type Config struct {
CorsAllowedOrigins map[string]bool

DebugHttp bool

CsrfEnabled bool
RedisConnection string
}

var Global Config
Expand Down Expand Up @@ -57,6 +60,9 @@ func (c *Config) Load() {
c.CookieSecure = getCookieSecure(c.GatewayUrl)

c.CorsAllowedOrigins = getCorsAllowedOrigins(getEnv("CORS_ALLOWED_ORIGINS", ""))

c.CsrfEnabled = getEnv("CSRF_ENABLED", "") == "true"
c.RedisConnection = getEnv("REDIS_CONNECTION", "localhost:6379")
}

func getEnv(key, def string) string {
Expand Down
5 changes: 5 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ func TestConfigLoad(t *testing.T) {
_ = os.Setenv("GATEWAY_URL", "https://gateway.dev.cash-track.app:8081")
_ = os.Setenv("HTTPS_ENABLED", "true")
_ = os.Setenv("CORS_ALLOWED_ORIGINS", "https://My.dev.cash-track.app:3001,https://Dev.cash-track.app:3000")
_ = os.Setenv("CSRF_ENABLED", "true")
_ = os.Setenv("REDIS_CONNECTION", "redis:1234")

config := &Config{}
config.Load()
Expand Down Expand Up @@ -42,6 +44,9 @@ func TestConfigLoad(t *testing.T) {

_, ok = config.CorsAllowedOrigins["https://dev.cash-track.app:3000"]
assert.Equal(t, true, ok)

assert.Equal(t, true, config.CsrfEnabled)
assert.Equal(t, "redis:1234", config.RedisConnection)
}

func TestConfigLoadUnexpectedApiUrl(t *testing.T) {
Expand Down
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/go-redis/redismock/v9 v9.2.0 // indirect
github.com/golang-jwt/jwt/v4 v4.5.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
Expand All @@ -23,6 +27,7 @@ require (
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.59.1 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/redis/go-redis/v9 v9.7.0 // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect
github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
Expand Down
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,20 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fasthttp/router v1.5.2 h1:ckJCCdV7hWkkrMeId3WfEhz+4Gyyf6QPwxi/RHIMZ6I=
github.com/fasthttp/router v1.5.2/go.mod h1:C8EY53ozOwpONyevc/V7Gr8pqnEjwnkFFqPo1alAGs0=
github.com/flf2ko/fasthttp-prometheus v0.1.0 h1:hj4K3TwJ2B7Fe2E7lWE/eb9mtb7gBvwURXr4+iEFoCI=
github.com/flf2ko/fasthttp-prometheus v0.1.0/go.mod h1:5tGRWsJeP8ABLYovqPxa5c/zCgnsYUhhC1ivs/Kv/c4=
github.com/go-redis/redismock/v9 v9.2.0 h1:ZrMYQeKPECZPjOj5u9eyOjg8Nnb0BS9lkVIZ6IpsKLw=
github.com/go-redis/redismock/v9 v9.2.0/go.mod h1:18KHfGDK4Y6c2R0H38EUGWAdc7ZQS9gfYxc94k7rWT0=
github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=
github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
Expand All @@ -33,6 +41,8 @@ github.com/prometheus/common v0.59.1 h1:LXb1quJHWm1P6wq/U824uxYi4Sg0oGvNeUm1z5dJ
github.com/prometheus/common v0.59.1/go.mod h1:GpWM7dewqmVYcd7SmRaiWVe9SSqjf0UrwnYnpEZNuT0=
github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc=
github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=
github.com/redis/go-redis/v9 v9.7.0 h1:HhLSs+B6O021gwzl+locl0zEDnyNkxMtf/Z3NNBMa9E=
github.com/redis/go-redis/v9 v9.7.0/go.mod h1:f6zhXITC7JUJIlPEiBOTXxJgPLdZcA93GewI7inzyWw=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 h1:D0vL7YNisV2yqE55+q0lFuGse6U8lxlg7fYTctlT5Gc=
Expand Down
38 changes: 38 additions & 0 deletions headers/cookie/csrf.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package cookie

import (
"time"

"github.com/valyala/fasthttp"
)

const (
CsrfTokenCookieName = "cshtrkcsrf"
CsrfTokenTtl = time.Minute * 10
)

type CSRF struct {
Auth Auth
Token string
}

func ReadCSRFCookie(ctx *fasthttp.RequestCtx) CSRF {
csrf := CSRF{
Auth: ReadAuthCookie(ctx),
}

if val := ctx.Request.Header.Cookie(CsrfTokenCookieName); val != nil {
csrf.Token = string(val)
}

return csrf
}

func (c CSRF) WriteCookie(ctx *fasthttp.RequestCtx) {
if !c.Auth.IsLogged() {
ctx.Response.Header.SetCookie(newCookie(CsrfTokenCookieName, "", fasthttp.CookieExpireDelete))
return
}

ctx.Response.Header.SetCookie(newCookie(CsrfTokenCookieName, c.Token, time.Now().Add(CsrfTokenTtl)))
}
51 changes: 51 additions & 0 deletions headers/cookie/csrf_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package cookie

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/valyala/fasthttp"
)

func TestReadCSRFCookie(t *testing.T) {
ctx := fasthttp.RequestCtx{}
ctx.Request.Header.SetCookie(AccessTokenCookieName, "access_token")
ctx.Request.Header.SetCookie(CsrfTokenCookieName, "csrf_token")

csrf := ReadCSRFCookie(&ctx)

assert.Equal(t, "csrf_token", csrf.Token)
assert.Equal(t, true, csrf.Auth.IsLogged())
}

func TestWriteCSRFCookie(t *testing.T) {
for name, test := range map[string]struct {
csrf CSRF
expectedToken string
}{
"Logged": {
csrf: CSRF{
Auth: Auth{
AccessToken: "access_token",
},
Token: "csrf_token",
},
expectedToken: "csrf_token",
},
"Guest": {
csrf: CSRF{
Token: "csrf_token",
},
expectedToken: "",
},
} {
t.Run(name, func(t *testing.T) {
ctx := fasthttp.RequestCtx{}

test.csrf.WriteCookie(&ctx)

token := ctx.Response.Header.PeekCookie(CsrfTokenCookieName)
assert.Contains(t, string(token), test.expectedToken)
})
}
}
Loading