Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
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
12 changes: 8 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ ENV_APP_ENV_TYPE=local
ENV_APP_LOG_LEVEL=debug
ENV_APP_LOGS_DIR="./storage/logs/logs_%s.log"
ENV_APP_LOGS_DATE_FORMAT="2006_02_01"

# --- Auth
ENV_APP_TOKEN_PUBLIC="foo"
ENV_APP_TOKEN_PRIVATE="bar"
ENV_APP_MASTER_KEY=

# --- DB
ENV_DB_USER_NAME="gus"
Expand All @@ -24,3 +21,10 @@ CADDY_LOGS_PATH="./storage/logs/caddy"
# --- Docker (Local envs)
ENV_DOCKER_USER="gocanto"
ENV_DOCKER_USER_GROUP="ggroup"

# --- Testing Token
# These variables are not intended to be used in production, but in the console interface (option: 3).
# This procedure facilitates the signatures creation for local testing/development.
# For more info, please see: cli/main.go
ENV_LOCAL_TOKEN_ACCOUNT=
ENV_LOCAL_TOKEN_SECRET=
4 changes: 0 additions & 4 deletions .env.prod.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@ ENV_APP_LOG_LEVEL=debug
ENV_APP_LOGS_DIR="./storage/logs/logs_%s.log"
ENV_APP_LOGS_DATE_FORMAT="2006_02_01"

# --- Auth
ENV_APP_TOKEN_PUBLIC=""
ENV_APP_TOKEN_PRIVATE=""

# --- DB
ENV_DB_PORT=
ENV_DB_HOST=
Expand Down
14 changes: 13 additions & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,19 @@ jobs:
docker pull ghcr.io/oullin/oullin_api:$IMAGE_TAG
docker pull ghcr.io/oullin/oullin_proxy:$IMAGE_TAG

echo "----- Images before re-tag -----"
docker images | grep api-api
echo "-------------------------------"

echo "🏷️ Retagging for Compose…"
docker tag ghcr.io/oullin/oullin_api:$IMAGE_TAG api-api:latest
docker tag ghcr.io/oullin/oullin_proxy:$IMAGE_TAG api-caddy_prod:latest

echo "----- Images after re-tag -----"
docker images | grep api-api
echo "-------------------------------"

echo "🧹 Pruning old, unused Docker images ..."
docker image prune -af
docker image prune -f

echo "✅ Latest images pulled successfully to VPS!"
27 changes: 21 additions & 6 deletions boost/app.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package boost

import (
"fmt"
"github.com/oullin/database"
"github.com/oullin/database/repository"
"github.com/oullin/env"
"github.com/oullin/pkg"
"github.com/oullin/pkg/auth"
"github.com/oullin/pkg/http/middleware"
"github.com/oullin/pkg/llogs"
baseHttp "net/http"
Expand All @@ -18,31 +21,43 @@ type App struct {
db *database.Connection
}

func MakeApp(env *env.Environment, validator *pkg.Validator) *App {
func MakeApp(env *env.Environment, validator *pkg.Validator) (*App, error) {
tokenHandler, err := auth.MakeTokensHandler(
[]byte(env.App.MasterKey),
)

if err != nil {
return nil, fmt.Errorf("bootstrapping error > could not create a token handler: %w", err)
}

db := MakeDbConnection(env)

app := App{
env: env,
validator: validator,
logs: MakeLogs(env),
sentry: MakeSentry(env),
db: MakeDbConnection(env),
db: db,
}

router := Router{
Env: env,
Mux: baseHttp.NewServeMux(),
Pipeline: middleware.Pipeline{
Env: env,
Env: env,
ApiKeys: &repository.ApiKeys{DB: db},
TokenHandler: tokenHandler,
},
}

app.SetRouter(router)

return &app
return &app, nil
}

func (a *App) Boot() {
if a.router == nil {
panic("Router is not set")
if a == nil || a.router == nil {
panic("bootstrapping error > Invalid setup")
}

router := *a.router
Expand Down
16 changes: 3 additions & 13 deletions boost/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"github.com/oullin/database"
"github.com/oullin/env"
"github.com/oullin/pkg"
"github.com/oullin/pkg/auth"
"github.com/oullin/pkg/llogs"
"log"
"strconv"
Expand Down Expand Up @@ -60,15 +59,10 @@ func MakeEnv(validate *pkg.Validator) *env.Environment {

port, _ := strconv.Atoi(env.GetEnvVar("ENV_DB_PORT"))

token := auth.Token{
Public: env.GetEnvVar("ENV_APP_TOKEN_PUBLIC"),
Private: env.GetEnvVar("ENV_APP_TOKEN_PRIVATE"),
}

app := env.AppEnvironment{
Name: env.GetEnvVar("ENV_APP_NAME"),
Type: env.GetEnvVar("ENV_APP_ENV_TYPE"),
Credentials: token,
Name: env.GetEnvVar("ENV_APP_NAME"),
Type: env.GetEnvVar("ENV_APP_ENV_TYPE"),
MasterKey: env.GetEnvVar("ENV_APP_MASTER_KEY"),
}

db := env.DBEnvironment{
Expand Down Expand Up @@ -106,10 +100,6 @@ func MakeEnv(validate *pkg.Validator) *env.Environment {
panic(errorSuffix + "invalid [Sql] model: " + validate.GetErrorsAsJason())
}

if _, err := validate.Rejects(token); err != nil {
panic(errorSuffix + "invalid [token] model: " + validate.GetErrorsAsJason())
}

if _, err := validate.Rejects(logsCreds); err != nil {
panic(errorSuffix + "invalid [logs Creds] model: " + validate.GetErrorsAsJason())
}
Expand Down
4 changes: 2 additions & 2 deletions boost/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ type Router struct {

func (r *Router) PipelineFor(apiHandler http.ApiHandler) baseHttp.HandlerFunc {
tokenMiddleware := middleware.MakeTokenMiddleware(
r.Env.App.Credentials,
r.Pipeline.TokenHandler,
r.Pipeline.ApiKeys,
)

return http.MakeApiHandler(
r.Pipeline.Chain(
apiHandler,
middleware.UsernameCheck,
tokenMiddleware.Handle,
),
)
Expand Down
60 changes: 38 additions & 22 deletions caddy/Caddyfile.prod
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,50 @@
# Caddy will automatically provision a Let's Encrypt certificate.

oullin.io {
# Enable compression to reduce bandwidth usage.
encode gzip zstd

# Add security-related headers to protect against common attacks.
header {
# Enable HSTS to ensure browsers only connect via HTTPS.
Strict-Transport-Security "max-age=31536000;"
# Prevent clickjacking attacks.
X-Frame-Options "SAMEORIGIN"
# Prevent content type sniffing.
X-Content-Type-Options "nosniff"
# Enhances user privacy.
Referrer-Policy "strict-origin-when-cross-origin"
}

log {
# Enable compression to reduce bandwidth usage.
encode gzip zstd

# Add security-related headers to protect against common attacks.
header {
# Enable HSTS to ensure browsers only connect via HTTPS.
Strict-Transport-Security "max-age=31536000;"
# Prevent clickjacking attacks.
X-Frame-Options "SAMEORIGIN"
# Prevent content type sniffing.
X-Content-Type-Options "nosniff"
# Enhances user privacy.
Referrer-Policy "strict-origin-when-cross-origin"
}

log {
output file /var/log/caddy/oullin.io.log {
roll_size 10mb # Rotate logs after they reach 10MB
roll_keep 5 # Keep the last 5 rotated log files
roll_size 10mb # Rotate logs after they reach 10MB
roll_keep 5 # Keep the last 5 rotated log files
}

format json
}

# Reverse proxy all requests to the Go application service.
# 'api' is the service name defined in docker-compose.yml.
reverse_proxy api:8080 {
# Set timeouts to prevent slow backends from holding up resources.
# Reverse-proxy all requests to the Go API, forwarding Host + auth headers
reverse_proxy {
# Tell Caddy which upstream to send to
to api:8080

# Preserve the original Host header
header_up Host {host}

# Forward the client-sent auth headers
header_up X-API-Username {http.request.header.X-API-Username}
header_up X-API-Key {http.request.header.X-API-Key}
header_up X-API-Signature {http.request.header.X-API-Signature}

# Todo: Remove!
# *** DEBUG: echo back to client what Caddy actually saw ***
header_down X-Debug-Username {http.request.header.X-API-Username}
header_down X-Debug-Key {http.request.header.X-API-Key}
header_down X-Debug-Signature {http.request.header.X-API-Signature}

# Transport timeouts
transport http {
dial_timeout 10s
response_header_timeout 30s
Expand Down
33 changes: 33 additions & 0 deletions cli/accounts/factory.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package accounts

import (
"fmt"
"github.com/oullin/database"
"github.com/oullin/database/repository"
"github.com/oullin/env"
"github.com/oullin/pkg/auth"
)

type Handler struct {
IsDebugging bool
Env *env.Environment
Tokens *repository.ApiKeys
TokenHandler *auth.TokenHandler
}

func MakeHandler(db *database.Connection, env *env.Environment) (*Handler, error) {
tokenHandler, err := auth.MakeTokensHandler(
[]byte(env.App.MasterKey),
)

if err != nil {
return nil, fmt.Errorf("failed to make token handler: %v", err)
}

return &Handler{
Env: env,
IsDebugging: false,
Tokens: &repository.ApiKeys{DB: db},
TokenHandler: tokenHandler,
}, nil
}
90 changes: 90 additions & 0 deletions cli/accounts/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package accounts

import (
"fmt"
"github.com/oullin/database"
"github.com/oullin/pkg/auth"
"github.com/oullin/pkg/cli"
)

func (h Handler) CreateAccount(accountName string) error {
token, err := h.TokenHandler.SetupNewAccount(accountName)

if err != nil {
return fmt.Errorf("failed to create the given account [%s] tokens pair: %v", accountName, err)
}

_, err = h.Tokens.Create(database.APIKeyAttr{
AccountName: token.AccountName,
SecretKey: token.EncryptedSecretKey,
PublicKey: token.EncryptedPublicKey,
})

if err != nil {
return fmt.Errorf("failed to create account [%s]: %v", accountName, err)
}

cli.Successln("Account created successfully.\n")

return nil
}

func (h Handler) ReadAccount(accountName string) error {
item := h.Tokens.FindBy(accountName)

if item == nil {
return fmt.Errorf("the given account [%s] was not found", accountName)
}

token, err := h.TokenHandler.DecodeTokensFor(
item.AccountName,
item.SecretKey,
item.PublicKey,
)

if err != nil {
return fmt.Errorf("could not decode the given account [%s] keys: %v", item.AccountName, err)
}

cli.Successln("\nThe given account has been found successfully!\n")
cli.Blueln(" > " + fmt.Sprintf("Account name: %s", token.AccountName))
cli.Blueln(" > " + fmt.Sprintf("Public Key: %s", token.PublicKey))
cli.Blueln(" > " + fmt.Sprintf("Secret Key: %s", token.SecretKey))
cli.Blueln(" > " + fmt.Sprintf("API Signature: %s", auth.CreateSignatureFrom(token.AccountName, token.SecretKey)))
cli.Warningln("----- Encrypted Values -----")
cli.Magentaln(" > " + fmt.Sprintf("Public Key: %x", token.EncryptedPublicKey))
cli.Magentaln(" > " + fmt.Sprintf("Secret Key: %x", token.EncryptedSecretKey))
fmt.Println(" ")

return nil
}

func (h Handler) CreateSignature(accountName string) error {
item := h.Tokens.FindBy(accountName)

if item == nil {
return fmt.Errorf("the given account [%s] was not found", accountName)
}

token, err := h.TokenHandler.DecodeTokensFor(
item.AccountName,
item.SecretKey,
item.PublicKey,
)

if err != nil {
return fmt.Errorf("could not decode the given account [%s] keys: %v", item.AccountName, err)
}

signature := auth.CreateSignatureFrom(token.AccountName, token.SecretKey)

cli.Successln("\nThe given account has been found successfully!\n")
cli.Blueln(" > " + fmt.Sprintf("Account name: %s", token.AccountName))
cli.Blueln(" > " + fmt.Sprintf("Public Key: %s", auth.SafeDisplay(token.PublicKey)))
cli.Blueln(" > " + fmt.Sprintf("Secret Key: %s", auth.SafeDisplay(token.SecretKey)))
cli.Warningln("----- Encrypted Values -----")
cli.Magentaln(" > " + fmt.Sprintf("Signature: %s", signature))
fmt.Println(" ")

return nil
}
Loading
Loading