Skip to content

Commit

Permalink
init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
NxPKG committed May 25, 2024
1 parent 5ae76fb commit 496b102
Show file tree
Hide file tree
Showing 11 changed files with 359 additions and 1 deletion.
55 changes: 55 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
name: Publish

on:
release:
types: [released]

jobs:
verify:
name: Verify tag
runs-on: ubuntu-latest

outputs:
valid: ${{ steps.check-tag.outputs.valid }}

steps:
- name: Check Tag
id: check-tag
run: |
if [[ ${{ github.ref }} =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "valid=true" >> $GITHUB_OUTPUT
fi
publish:
if: needs.verify.outputs.valid == 'true'
name: Release
runs-on: ubuntu-latest
needs: verify

steps:
- name: Checkout project
uses: actions/checkout@v3

- name: Get tag
id: meta
run: |
TAG=$(echo $GITHUB_REF | cut -d / -f 3)
echo "tag=${TAG}" >> $GITHUB_OUTPUT
- name: Log in to the Container registry
uses: docker/login-action@v2
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

- name: Build and push Docker image
uses: docker/build-push-action@v3
with:
context: .
push: true
build-args: |
VERSION=${{ steps.meta.outputs.tag }}
tags: |
ghcr.io/khulnasoft-lab/rproxy:latest
ghcr.io/khulnasoft-lab/rproxy:${{ steps.meta.outputs.tag }}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
rproxy
*.yaml
33 changes: 33 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
FROM golang:1.22.1-alpine3.19 AS base

RUN apk --update upgrade && apk --no-cache --update-cache --upgrade --latest add ca-certificates build-base gcc

WORKDIR /build

ADD go.mod go.mod
ADD go.sum go.sum

ENV GO111MODULE on
ENV CGO_ENABLED 1

RUN go mod download

ADD . .

ARG VERSION

RUN go build \
-ldflags="-X main.version=${VERSION}" \
-o /usr/bin/rproxy

FROM alpine:3.16

RUN addgroup -S rproxy; \
adduser -S rproxy -G rproxy -D -u 10000 -s /bin/nologin;

COPY --from=base /usr/bin/rproxy /usr/bin/rproxy

USER 10000

ENTRYPOINT ["rproxy"]
CMD ["start", "--config", "/etc/rproxy/config.yaml"]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 KhulnaSoft Labs.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
53 changes: 52 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,52 @@
# rproxy
# Rproxy

Reverse Proxy with Basic Authentication

## Usage

Start it with:

```bash
$ go build
$ cat >> config.yaml <<EOL
users:
- username: admin
password: pass
EOL
$ ./rproxy start
```

Use it like:

```bash
$ curl http://localhost:6634/
Unauthorized
$ curl http://admin:pass@localhost:6634/
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip",
"Authorization": "Basic dGVzdDp0ZXN0MQ==",
"Host": "httpbin.org",
"User-Agent": "curl/8.4.0",
"X-Amzn-Trace-Id": "Root=1-65f8675b-7f79a49a4d55a63170385c81"
},
"origin": "142.122.13.19",
"url": "https://httpbin.org/get"
}
```

## Docker

You can also use it with Docker:

```bash
$ docker pull ghcr.io/khulnasoft-lab/rproxy:latest
$ cat >> config.yaml <<EOL
users:
- username: admin
password: pass
EOL
$ docker run --rm -v $(PWD)/config.yaml:/etc/rproxy/config.yaml -p 6634:6634 ghcr.io/khulnasoft-lab/rproxy:latest
```
38 changes: 38 additions & 0 deletions auth/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package auth

import (
"crypto/subtle"
"net/http"

"github.com/khulnasoft-lab/rproxy/config"
)

func Middleware(handler http.HandlerFunc, config config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok {
respondUnauthorised(w)
return
}

allow := false
for _, user := range config.Users {
if subtle.ConstantTimeCompare([]byte(username), []byte(user.Username)) == 1 && subtle.ConstantTimeCompare([]byte(password), []byte(user.Password)) == 1 {
allow = true
break
}
}

if !allow {
respondUnauthorised(w)
return
}

handler(w, r)
}
}

func respondUnauthorised(w http.ResponseWriter) {
w.WriteHeader(401)
w.Write([]byte("Unauthorized\n"))
}
29 changes: 29 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package config

import (
"os"

"gopkg.in/yaml.v3"
)

type Config struct {
Users []User `yaml:"users"`
}

type User struct {
Username string `yaml:"username"`
Password string `yaml:"password"`
}

func Parse(path *string) (*Config, error) {
data, err := os.ReadFile(*path)
if err != nil {
return nil, err
}
config := Config{}
err = yaml.Unmarshal([]byte(data), &config)
if err != nil {
return nil, err
}
return &config, nil
}
14 changes: 14 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module github.com/khulnasoft-lab/rproxy

go 1.22

require (
github.com/urfave/cli/v2 v2.27.1
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
)
12 changes: 12 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/urfave/cli/v2 v2.27.1 h1:8xSQ6szndafKVRmfyeUMxkNUJQMjL1F2zmsZ+qHpfho=
github.com/urfave/cli/v2 v2.27.1/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
87 changes: 87 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package main

import (
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"

"github.com/khulnasoft-lab/rproxy/auth"
"github.com/khulnasoft-lab/rproxy/config"
"github.com/khulnasoft-lab/rproxy/proxy"
"github.com/urfave/cli/v2"
)

var (
version = "dev"
)

func start(c *cli.Context) error {
port := c.Int("port")
upstream := c.String("upstream")
configPath := c.String("config")

config, err := config.Parse(&configPath)
if err != nil {
log.Fatalf("Could not read configuration file: %v", err)
return err
}

upstreamURL, err := url.Parse(upstream)
if err != nil {
log.Fatalf("Could not parse upstream URL: %v", err)
return err
}
reverseProxy := proxy.NewReverseProxy(upstreamURL)
http.HandleFunc("/", auth.Middleware(reverseProxy.ServeHTTP, *config))

listener, err := net.Listen("tcp4", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatalf("Proxy could not start %v", err)
return err
}

if err := http.Serve(listener, nil); err != nil {
log.Fatalf("Proxy could not start %v", err)
return err
}

return nil
}

func main() {
app := cli.NewApp()
app.Name = "Rproxy"
app.Usage = "Reverse Proxy with Basic Authentication"
app.Version = version
app.Authors = []*cli.Author{
{
Name: "KhulnaSoft Labs.",
},
}
app.Commands = []*cli.Command{
{
Name: "start",
Usage: "Start the proxy",
Action: start,
Flags: []cli.Flag{
&cli.IntFlag{
Name: "port",
Usage: "Port used by the proxy",
Value: 6634,
}, &cli.StringFlag{
Name: "upstream",
Usage: "Upstream server to proxy to",
Value: "https://httpbin.org",
}, &cli.StringFlag{
Name: "config",
Usage: "Configuration file path",
Value: "config.yaml",
},
},
},
}
app.Run(os.Args)
}
16 changes: 16 additions & 0 deletions proxy/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package proxy

import (
"net/http/httputil"
"net/url"
)

func NewReverseProxy(upstreamURL *url.URL) *httputil.ReverseProxy {
return &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.Out.URL.Host = upstreamURL.Host
r.Out.URL.Scheme = upstreamURL.Scheme
r.Out.Host = upstreamURL.Host
},
}
}

0 comments on commit 496b102

Please sign in to comment.