Repository: prashantgupta24/firewalld-rest Branch: master Commit: 114802311372 Files: 24 Total size: 55.1 KB Directory structure: gitextract_0bo9mjds/ ├── .gitignore ├── Dockerfile ├── LICENSE ├── Makefile ├── README.md ├── cmd/ │ └── main.go ├── db/ │ ├── db.go │ └── fileType.go ├── firewallcmd/ │ └── util.go ├── firewalld-rest.service ├── go.mod ├── go.sum ├── ip/ │ ├── handler.go │ ├── handler_test.go │ └── ip.go ├── k8s/ │ ├── ingress.yaml │ ├── svc-nodeport.yaml │ └── svc.yaml └── route/ ├── handler.go ├── handler_test.go ├── middleware.go ├── publicCert.go ├── response.go └── route.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .env *.db build/ # coverage *.html *.out ================================================ FILE: Dockerfile ================================================ FROM golang:alpine as builder RUN mkdir /build ADD . /build/ WORKDIR /build RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' ./cmd/main.go FROM scratch COPY --from=builder /build/main /app/ WORKDIR /app CMD ["./main"] ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2020 Prashant Gupta 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. ================================================ FILE: Makefile ================================================ COVER_PROFILE=cover.out COVER_PROFILE_TEMP=cover.tmp.out COVER_HTML=cover.html .PHONY: build $(COVER_PROFILE) $(COVER_HTML) all: coverage vet coverage: $(COVER_HTML) $(COVER_HTML): $(COVER_PROFILE) ignoreFiles go tool cover -html=$(COVER_PROFILE) -o $(COVER_HTML) ignoreFiles: cat $(COVER_PROFILE_TEMP) | grep -v "middleware.go" | grep -v "route.go" > $(COVER_PROFILE) $(COVER_PROFILE): env=local go test -v -failfast -race -coverprofile=$(COVER_PROFILE_TEMP) ./... vet: go vet ./... start-local: clean-db #for testing on your local system without firewalld env=local go run cmd/main.go start-server: go run cmd/main.go build-linux: # example: make build-linux DB_PATH=/dir/to/db env GOOS=linux GOARCH=amd64 go build -ldflags "-X github.com/prashantgupta24/firewalld-rest/db.pathFromEnv=$(DB_PATH)" -o build/firewalld-rest cmd/main.go local-build: go build -ldflags "-X github.com/prashantgupta24/firewalld-rest/db.pathFromEnv=$(DB_PATH)" -o build/firewalld-rest cmd/main.go copy: build-linux scp build/firewalld-rest root@:/root/rest clean-db: rm -f *.db test: env=local go test -v -failfast -race ./... ================================================ FILE: README.md ================================================ [![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go) [![Go Report Card](https://goreportcard.com/badge/github.com/prashantgupta24/firewalld-rest)](https://goreportcard.com/report/github.com/prashantgupta24/firewalld-rest) [![codecov](https://codecov.io/gh/prashantgupta24/firewalld-rest/branch/master/graph/badge.svg)](https://codecov.io/gh/prashantgupta24/firewalld-rest) [![version][version-badge]][releases] # Firewalld-rest A REST application to dynamically update firewalld rules on a linux server. _Firewalld is a firewall management tool for Linux operating systems._ ## Purpose If you have seen this message when you login to your linux server: ``` There were 534 failed login attempts since the last successful login. ``` Then this idea is for **you**. The simple idea behind this is to have a completely isolated system, a system running Firewalld that does not permit SSH access to any IP address by default so there are no brute-force attacks. The only way to access the system is by communicating with a REST application running on the server through a valid request containing your public IP address. The REST application validates your request (it checks for a valid JWT, covered later), and if the request is valid, it will add your IP to the firewalld rule for the public zone for SSH, which gives **only your IP** SSH access to the machine. Once you are done using the machine, you can remove your IP interacting with the same REST application, and it changes rules in firewalld, shutting off SSH access and isolating the system again. ## Comparison with fail2ban This repo takes a proactive approach rather than a reactive approach taken by `fail2ban`. `fail2ban` dynamically alters the firewall rules to ban addresses that have unsuccessfully attempted to login a certain number of times. It is reactive - it allows people to try and login to the server, but bans those who are unsuccessful in doing so after a certain number of times. It is like appointing a guard (aka firewall) outside a locked building who checks for suspicious activity and the guard is told by `fail2ban` to ban anyone who tries to open the lock unsuccessfully many times. Firewalld-rest is more of a proactive approach. Let me explain. ### Proactive approach By using the approach presented in this repo, you still add a guard (aka firewall) like you did for fail2ban in front of your locked building (aka the server). But there are 2 main differences here: 1. This guard is told to not let **anyone** come near the building by default, so that no one is ever close enough to the lock to try their keys. (This means that the default firewall rules are set up by default in such a way so that no one can even try to SSH to the server). 2. You can talk to the guard (aka firewall) using this repo, and convince the guard to allow you near the building, provided you possess a certain key (an **RS256** type, covered later). (This means that using the REST interface provided by this repo, you proactively alter firewall rules to allow ONLY your IP to try and login to the server) `Note`: Once you are allowed through by the firewall, you still need to have the key to login to the server. > It is proactive - You proactively talk to the REST interface and alter the firewall rules to allow your IP to try and login. **TL;DR** | `fail2ban` | `firewalld-rest ` | | ---------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `dynamically` alters firewall rules to ban IP addresses that have unsuccessfully attempted to login to server a certain number of times. | provides REST interface to `manually` alter firewall rules to allow ONLY your IP to try and login to server. No IP apart from yours can even try to login to server. | | `Reactive` - it alters firewall rules _after_ unsuccessfully attempts | `Proactive` - you alter firewall rules _before_ trying to login to server | > Note: I am not saying one approach is better than the other. They are just different approaches to the same problem. ## Table of Contents - [Purpose](#purpose) - [Comparison with fail2ban](#comparison-with-fail2ban) - [Proactive approach](#proactive-approach) - [Table of Contents](#table-of-contents) - [1. Pre-requisites](#1-pre-requisites) - [2. About the application](#2-about-the-application) - [2.1 Firewall-cmd](#21-firewall-cmd) - [2.2 Database](#22-database) - [2.3 Authorization](#23-authorization) - [2.4 Tests](#24-tests) - [3. How to install and use on server](#3-how-to-install-and-use-on-server) - [3.1 Generate JWT](#31-generate-jwt) - [3.2 Build the application](#32-build-the-application) - [3.3 Copy binary file over to server](#33-copy-binary-file-over-to-server) - [3.4 Remove SSH from public firewalld zone](#34-remove-ssh-from-public-firewalld-zone) - [3.5 Expose the REST application](#35-expose-the-rest-application) - [3.5.1 Single node cluster](#351-single-node-cluster) - [3.5.2 Multi-node cluster](#352-multi-node-cluster) - [3.6 Configure linux systemd service](#36-configure-linux-systemd-service) - [3.7 Start and enable systemd service.](#37-start-and-enable-systemd-service) - [3.8 IP JSON](#38-ip-json) - [3.9 Interacting with the REST application](#39-interacting-with-the-rest-application) - [3.9.1 Index page](#391-index-page) - [Sample query](#sample-query) - [3.9.2 Show all IPs](#392-show-all-ips) - [Sample query](#sample-query-1) - [3.9.3 Add new IP](#393-add-new-ip) - [Sample query](#sample-query-2) - [3.9.4 Show if IP is present](#394-show-if-ip-is-present) - [Sample query](#sample-query-3) - [3.9.5 Delete IP](#395-delete-ip) - [Sample query](#sample-query-4) - [4. Helpful tips/links](#4-helpful-tipslinks) - [5. Commands for generating public/private key](#5-commands-for-generating-publicprivate-key) - [6. Possible enhancements](#6-possible-enhancements) ## 1. Pre-requisites This repo assumes you have: 1. A linux server with `firewalld` installed. 1. `root` access to the server. (without `root` access, the application will not be able to run the `firewall-cmd` commands needed to add the rule for SSH access) 1. Some way of exposing the application externally (there are examples in this repo on how to use Kubernetes to expose the service) ## 2. About the application ### 2.1 Firewall-cmd Firewall-cmd is the command line client of the firewalld daemon. Through this, the REST application adds the rule specific to the IP address sent in the request. The syntax of adding a rule for an IP address is: `firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="10.xx.xx.xx/32" port protocol="tcp" port="22" accept'` Once the rule for the IP address has been added, the IP address is stored in a database (covered next). The database is just to keep track of all IPs that have rules created for them. ### 2.2 Database The database for the application stores the list of IP addresses that have rules created for them which allow SSH access for those IPs. Once you interact with the REST application and the application creates a firewalld rule specific to your IP address, then your IP address is stored in the database. It is important that the database is maintained during server restarts, otherwise there may be discrepancy between the IP addresses having firewalld rules and IP addresses stored in the database. > Note: Having an IP in the database does not mean that IP address will be given SSH access. The database is just a way to reference all the IPs with rules created in firewalld. The application uses a file type database for now. The architecture of the code allows easy integration of any other type of databases. The interface in db.go is what is required to be fulfilled to introduce a new type of database. ### 2.3 Authorization The application uses `RS256` type algorithm to verify the incoming requests. > RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. The public certificate is in this file [publicCert.go](https://github.com/prashantgupta24/firewalld-rest/blob/master/route/publicCert.go), which is something that will have to be changed before you can use it. (more information on how to create a new one later). ### 2.4 Tests The tests can be run using `make test`. The emphasis has been given to testing the handler functions and making sure that IPs get added and removed successfully from the database. I still have to figure out how to actually automate the tests for the firewalld rules (contributions are welcome!) ## 3. How to install and use on server ### 3.1 Generate JWT Update the file [publicCert.go](https://github.com/prashantgupta24/firewalld-rest/blob/master/route/publicCert.go) with your own `public cert` for which you have the private key. If you want to create a new set, see the section on [generating your own public/private key](#5-commands-for-generating-publicprivate-key). Once you have your own public and private key pair, then after updating the file above, you can go to `jwt.io` and generate a valid JWT using `RS256 algorithm` (the payload doesn't matter). You will be using that JWT to make calls to the REST application, so keep the JWT safe. ### 3.2 Build the application Run the command: ``` make build-linux DB_PATH=/dir/to/db/ ``` It will create a binary under the build directory, called `firewalld-rest`. The `DB_PATH=/dir/to/keep/db` statement sets the path where the `.db` file will be saved **on the server**. It should be saved in a protected location such that it is not accidentally deleted on server restart or by any other user. A good place for it could be the same directory where you will copy the binary over to (in the next step). That way you will not forget where it is. If `DB_PATH` variable is not set, the db file will be created by default under `/`. (_This happens because the binary is run by systemd. If we manually ran the binary file on the server, the db file would be created in the same directory._) Once the binary is built, it should contain everything required to run the application on a linux based server. ### 3.3 Copy binary file over to server ``` scp build/firewalld-rest root@:/root/rest ``` _Note_: if you want to change the directory where you want to keep the binary, then make sure you edit the `firewalld-rest.service` file, as the `linux systemd service` definition example in this repo expects the location of the binary to be `/root/rest`. ### 3.4 Remove SSH from public firewalld zone This is to remove SSH access from the public zone, which will cease SSH access from everywhere. SSH into the server, and run the following command: ``` firewall-cmd --zone=public --remove-service=ssh --permanent ``` then reload (since we are using `--permanent`): ``` firewall-cmd --reload ``` This removes ssh access for everyone. This is where the application will come into play, and we enable access based on IP. **Confirmation for the step**: ``` firewall-cmd --zone=public --list-all ``` _Notice the `ssh` service will not be listed in public zone anymore._ Also try SSH access into the server from another terminal. It should reject the attempt. ### 3.5 Expose the REST application The REST application can be exposed in a number of different ways, I have 2 examples on how it can be exposed: 1. Using a `NodePort` kubernetes service ([link](https://github.com/prashantgupta24/firewalld-rest/blob/master/k8s/svc-nodeport.yaml)) 2. Using `ingress` along with a kubernetes service ([link](https://github.com/prashantgupta24/firewalld-rest/blob/master/k8s/ingress.yaml)) #### 3.5.1 Single node cluster For a single-node cluster, see the kubernetes service example [here](https://github.com/prashantgupta24/firewalld-rest/blob/master/k8s/svc-nodeport.yaml). The important thing to note is that we manually add the `Endpoints` resource for the service, which points to our node's private IP address and port `8080`. Once deployed, your service might look like this: ``` kubernetes get svc external-rest | NodePort | 10.xx.xx.xx | 169.xx.xx.xx | 8080:31519/TCP ``` Now, you can interact with the application on: > 169.xx.xx.xx:31519/m1/ _Note: Since there's only 1 node in the cluster, you will only ever use `/m1`. For more than 1 node, see the next section._ #### 3.5.2 Multi-node cluster For a multi-node cluster, an ingress resource would be highly beneficial. The **first** step would be to create the kubernetes service in each individual node, using the example [here](https://github.com/prashantgupta24/firewalld-rest/blob/master/k8s/svc.yaml). The important thing to note is that we manually add the `Endpoints` resource for the service, which points to our node's private IP address and port `8080`. The **second** step is the [ingress](https://github.com/prashantgupta24/firewalld-rest/blob/master/k8s/ingress.yaml) resource. It redirects different routes to different nodes in the cluster. For example, in the ingress file above, A request to `/m1` will be redirected to the `first` node, a request to `/m2` will be redirected to the `second` node, and so on. This will let you control each node's individual SSH access through a single endpoint. ### 3.6 Configure linux systemd service See [this](https://github.com/prashantgupta24/firewalld-rest/blob/master/firewalld-rest.service) for an example of a linux systemd service. The `.service` file should be placed under `etc/systemd/system` directory. **Note**: This service assumes your binary is at `/root/rest/firewalld-rest`. You can change that in the file above. ### 3.7 Start and enable systemd service. **Start** ``` systemctl start firewalld-rest ``` **Logs** You can see the logs for the service using: ``` journalctl -r ``` **Enable** ``` systemctl enable firewalld-rest ``` ### 3.8 IP JSON This is how the IP JSON looks like, so that you know how you have to pass your IP and domain to the application: ``` type IP struct { IP string `json:"ip"` Domain string `json:"domain"` } ``` ### 3.9 Interacting with the REST application #### 3.9.1 Index page ``` route{ "Index Page", "GET", "/", } ``` ##### Sample query ``` curl --location --request GET ':8080/m1' \ --header 'Authorization: Bearer ' ``` #### 3.9.2 Show all IPs ``` route{ "Show all IPs present", "GET", "/ip", } ``` ##### Sample query ``` curl --location --request GET ':8080/m1/ip' \ --header 'Authorization: Bearer ' ``` #### 3.9.3 Add new IP ``` route{ "Add New IP", "POST", "/ip", } ``` ##### Sample query ``` curl --location --request POST ':8080/m1/ip' \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data-raw '{"ip":"10.xx.xx.xx","domain":"example.com"}' ``` #### 3.9.4 Show if IP is present ``` route{ "Show if particular IP is present", "GET", "/ip/{ip}", } ``` ##### Sample query ``` curl --location --request GET ':8080/m1/ip/10.xx.xx.xx' \ --header 'Authorization: Bearer ' ``` #### 3.9.5 Delete IP ``` route{ "Delete IP", "DELETE", "/ip/{ip}", } ``` ##### Sample query ``` curl --location --request DELETE ':8080/m1/ip/10.xx.xx.xx' \ --header 'Authorization: Bearer ' ``` ## 4. Helpful tips/links - ### 4.1 Creating custom kubernetes endpoint - https://theithollow.com/2019/02/04/kubernetes-endpoints/ - ### 4.2 Firewalld rules - https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-using-firewalld-on-centos-7 #### 4.2.1 Useful commands ``` firewall-cmd --get-default-zone firewall-cmd --get-active-zones firewall-cmd --list-all-zones | less firewall-cmd --zone=public --list-sources firewall-cmd --zone=public --list-services firewall-cmd --zone=public --list-all firewall-cmd --zone=public --add-service=ssh --permanent firewall-cmd --zone=internal --add-source=70.xx.xx.xxx/32 --permanent firewall-cmd --reload ``` #### 4.2.2 Rich rules `firewall-cmd --permanent --zone=public --list-rich-rules` `firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="10.10.99.10/32" port protocol="tcp" port="22" accept'` `firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.100.0/24" invert="True" drop'` > Reject will reply back with an ICMP packet noting the rejection, while a drop will just silently drop the traffic and do nothing else, so a drop may be preferable in terms of security as a reject response confirms the existence of the system as it is rejecting the request. #### 4.2.3 Misc tips > --add-source=IP can be used to add an IP address or range of addresses to a zone. This will mean that if any source traffic enters the systems that matches this, the zone that we have set will be applied to that traffic. In this case we set the ‘testing’ zone to be associated with traffic from the 10.10.10.0/24 range. ``` [root@centos7 ~]# firewall-cmd --permanent --zone=testing --add-source=10.10.10.0/24 success ``` - ### 4.3 Using JWT in Go - https://www.thepolyglotdeveloper.com/2017/03/authenticate-a-golang-api-with-json-web-tokens/ - ### 4.4 Using golang Exec - https://stackoverflow.com/questions/39151420/golang-executing-command-with-spaces-in-one-of-the-parts - ### 4.5 Systemd services - https://medium.com/@benmorel/creating-a-linux-service-with-systemd-611b5c8b91d6 - https://www.digitalocean.com/community/tutorials/understanding-systemd-units-and-unit-files - [Logs using journalctl](https://www.linode.com/docs/quick-answers/linux/how-to-use-journalctl/) - ### 4.6 Using LDFlags in golang - https://www.digitalocean.com/community/tutorials/using-ldflags-to-set-version-information-for-go-applications ## 5. Commands for generating public/private key ``` openssl genrsa -key private-key-sc.pem openssl req -new -x509 -key private-key-sc.pem -out public.cert ``` [version-badge]: https://img.shields.io/github/v/release/prashantgupta24/firewalld-rest [releases]: https://github.com/prashantgupta24/firewalld-rest/releases ## 6. Possible enhancements - Rate limiting the number of requests that can be made to the application ================================================ FILE: cmd/main.go ================================================ package main import ( "fmt" "log" "net/http" "github.com/prashantgupta24/firewalld-rest/route" ) func main() { fmt.Println("starting application") router := route.NewRouter() log.Fatal(http.ListenAndServe(":8080", router)) } ================================================ FILE: db/db.go ================================================ package db //Instance DB interface for application type Instance interface { Type() string Register(v interface{}) //needed for fileType. Can be left blank for other types of db Save(v interface{}) error Load(v interface{}) error } ================================================ FILE: db/fileType.go ================================================ package db import ( "bytes" "encoding/gob" "fmt" "io" "log" "os" "path/filepath" "sync" ) var lock sync.Mutex var once sync.Once var pathFromEnv string //This will be set through the build command, see Makefile const ( fileName = "firewalld-rest.db" defaultPath = "./" ) //singleton reference var fileTypeInstance *fileType //fileType is the main struct for file database type fileType struct { path string } //GetFileTypeInstance returns the singleton instance of the filedb object func GetFileTypeInstance() Instance { once.Do(func() { path := defaultPath + fileName if pathFromEnv != "" { pathFromEnv = parsePath(pathFromEnv) pathFromEnv += fileName path = pathFromEnv } fileTypeInstance = &fileType{path: path} }) return fileTypeInstance } //Type of the db func (fileType *fileType) Type() string { return "fileType" } // Register interface with gob func (fileType *fileType) Register(v interface{}) { gob.Register(v) } // Save saves a representation of v to the file at path. func (fileType *fileType) Save(v interface{}) error { lock.Lock() defer lock.Unlock() f, err := os.Create(fileType.path) if err != nil { return err } defer f.Close() r, err := marshal(v) if err != nil { return err } _, err = io.Copy(f, r) return err } // Load loads the file at path into v. func (fileType *fileType) Load(v interface{}) error { fullPath, err := filepath.Abs(fileType.path) if err != nil { return fmt.Errorf("could not locate absolute path : %v", err) } if fileExists(fileType.path) { lock.Lock() defer lock.Unlock() f, err := os.Open(fileType.path) if err != nil { return err } defer f.Close() return unmarshal(f, v) } log.Printf("Db file not found, will be created here: %v\n", fullPath) return nil } // marshal is a function that marshals the object into an // io.Reader. var marshal = func(v interface{}) (io.Reader, error) { var buf bytes.Buffer e := gob.NewEncoder(&buf) err := e.Encode(v) if err != nil { return nil, err } return bytes.NewReader(buf.Bytes()), nil } // unmarshal is a function that unmarshals the data from the // reader into the specified value. var unmarshal = func(r io.Reader, v interface{}) error { d := gob.NewDecoder(r) err := d.Decode(v) if err != nil { return err } return nil } // fileExists checks if a file exists and is not a directory before we // try using it to prevent further errors. func fileExists(filename string) bool { info, err := os.Stat(filename) if os.IsNotExist(err) { return false } return !info.IsDir() } func parsePath(path string) string { lastChar := path[len(path)-1:] if lastChar != "/" { path += "/" } return path } ================================================ FILE: firewallcmd/util.go ================================================ package firewallcmd import ( "fmt" "os/exec" ) //EnableRichRuleForIP enables rich rule for IP access + reloads //example: //firewall-cmd --permanent --zone=public --add-rich-rule='rule family="ipv4" source address="10.10.99.10/32" port protocol="tcp" port="22" accept' func EnableRichRuleForIP(ipAddr string) (string, error) { cmd1 := exec.Command(`firewall-cmd`, `--permanent`, "--zone=public", `--add-rich-rule=rule family="ipv4" source address="`+ipAddr+`/32" port protocol="tcp" port="22" accept`) //uncomment for debugging // for _, v := range cmd1.Args { // fmt.Println(v) // } output1, err1 := cmd1.CombinedOutput() if err1 != nil { return cmd1.String(), err1 } fmt.Printf("rich rule added successfully for ip %v : %v", ipAddr, string(output1)) cmd2, output2, err2 := reload() if err2 != nil { return cmd2.String(), err2 } fmt.Printf("firewalld reloaded successfully : %v", string(output2)) return "", nil } //DisableRichRuleForIP disables rich rule for IP access + reloads func DisableRichRuleForIP(ipAddr string) (string, error) { cmd1 := exec.Command(`firewall-cmd`, `--permanent`, "--zone=public", `--remove-rich-rule=rule family="ipv4" source address="`+ipAddr+`/32" port protocol="tcp" port="22" accept`) output1, err1 := cmd1.CombinedOutput() if err1 != nil { return cmd1.String(), err1 } fmt.Printf("rich rule deleted successfully for ip %v : %v", ipAddr, string(output1)) cmd2, output2, err2 := reload() if err2 != nil { return cmd2.String(), err2 } fmt.Printf("firewalld reloaded successfully : %v", string(output2)) return "", nil } //reload reloads firewall for setting to take effect func reload() (*exec.Cmd, []byte, error) { cmd := exec.Command("firewall-cmd", "--reload") output, err := cmd.CombinedOutput() return cmd, output, err } ================================================ FILE: firewalld-rest.service ================================================ [Unit] Description=Firewalld rest service After=network.target [Service] Type=simple Restart=always RestartSec=1 User=root ExecStart=/root/rest/firewalld-rest [Install] WantedBy=multi-user.target ================================================ FILE: go.mod ================================================ module github.com/prashantgupta24/firewalld-rest go 1.14 require ( github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/gorilla/mux v1.7.4 ) ================================================ FILE: go.sum ================================================ github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc= github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= ================================================ FILE: ip/handler.go ================================================ package ip import ( "fmt" "log" "sync" "github.com/prashantgupta24/firewalld-rest/db" ) var once sync.Once //singleton reference var handlerInstance *handlerStruct //handlerStruct for managing IP related tasks type handlerStruct struct { db db.Instance } //GetHandler gets singleton handler for IP management func GetHandler() Handler { once.Do(func() { dbInstance := db.GetFileTypeInstance() handlerInstance = &handlerStruct{ db: dbInstance, } ipStore, err := handlerInstance.loadIPStore() if err != nil { log.Fatal(err) } if len(ipStore) == 0 { //in case you want to store some IPs before hand // ipStore["1.2.3.4"] = &Instance{ // IP: "1.2.3.4", // Domain: "first.com", // } // ipStore["5.6.7.8"] = &Instance{ // IP: "5.6.7.8", // Domain: "second", // } handlerInstance.db.Register(ipStore) if err := handlerInstance.saveIPStore(ipStore); err != nil { log.Fatal(err) } } }) return handlerInstance } //GetIP from the db func (handler *handlerStruct) GetIP(ipAddr string) (*Instance, error) { ipStore, err := handler.loadIPStore() if err != nil { return nil, err } ip, ok := ipStore[ipAddr] if !ok { return nil, fmt.Errorf("record not found") } return ip, nil } //GetAllIPs from the db func (handler *handlerStruct) GetAllIPs() ([]*Instance, error) { ips := []*Instance{} ipStore, err := handler.loadIPStore() if err != nil { return nil, err } for _, ip := range ipStore { ips = append(ips, ip) } return ips, nil } //CheckIPExists checks if IP is in db func (handler *handlerStruct) CheckIPExists(ipAddr string) (bool, error) { ipStore, err := handler.loadIPStore() if err != nil { return false, err } _, ok := ipStore[ipAddr] if ok { return true, nil } return false, nil } //AddIP to the db func (handler *handlerStruct) AddIP(ip *Instance) error { ipStore, err := handler.loadIPStore() if err != nil { return err } _, ok := ipStore[ip.IP] if ok { return fmt.Errorf("ip already exists") } ipStore[ip.IP] = ip if err := handler.saveIPStore(ipStore); err != nil { return fmt.Errorf("error while saving to file : %v", err) } return nil } //DeleteIP from the db func (handler *handlerStruct) DeleteIP(ipAddr string) (*Instance, error) { ipStore, err := handler.loadIPStore() if err != nil { return nil, err } ip, ok := ipStore[ipAddr] if !ok { return nil, fmt.Errorf("record not found") } delete(ipStore, ipAddr) if err := handler.saveIPStore(ipStore); err != nil { return nil, fmt.Errorf("error while saving to file : %v", err) } return ip, nil } func (handler *handlerStruct) loadIPStore() (map[string]*Instance, error) { var ipStore = make(map[string]*Instance) if err := handler.db.Load(&ipStore); err != nil { return nil, fmt.Errorf("error while loading from file : %v", err) } return ipStore, nil } func (handler *handlerStruct) saveIPStore(ipStore map[string]*Instance) error { if err := handler.db.Save(ipStore); err != nil { return fmt.Errorf("error while saving to file : %v", err) } return nil } ================================================ FILE: ip/handler_test.go ================================================ package ip import ( "log" "os" "os/exec" "strings" "testing" ) var handler Handler var ipAddr string var ipInstance *Instance func setup() { handler = GetHandler() ipAddr = "10.20.30.40" ipInstance = &Instance{ IP: ipAddr, Domain: "test", } } func shutdown() { os.Remove("firewalld-rest.db") } func TestMain(m *testing.M) { setup() code := m.Run() shutdown() os.Exit(code) } func TestGetHandler(t *testing.T) { if handler == nil { t.Errorf("handler should not be nil") } } func TestGetAllIPsFileError(t *testing.T) { changeFilePermission("100") _, err := handler.GetAllIPs() if err == nil { t.Errorf("should have errored") } if err != nil && strings.Index(err.Error(), "permission denied") == -1 { t.Errorf("should have received permission error, instead got : %v", err) } changeFilePermission("644") } func TestGetAllIPs(t *testing.T) { ips, err := handler.GetAllIPs() if err != nil { t.Errorf("should not have errored, err : %v", err) } if len(ips) != 0 { t.Errorf("should have been an empty list, instead got : %v", len(ips)) } } func TestAddIPFileError(t *testing.T) { changeFilePermission("100") err := handler.AddIP(ipInstance) if err == nil { t.Errorf("should have errored") } if err != nil && strings.Index(err.Error(), "permission denied") == -1 { t.Errorf("should have received permission error, instead got : %v", err) } changeFilePermission("500") err = handler.AddIP(ipInstance) if err == nil { t.Errorf("should have errored") } if err != nil && strings.Index(err.Error(), "permission denied") == -1 { t.Errorf("should have received permission error, instead got : %v", err) } changeFilePermission("644") } func TestAddIP(t *testing.T) { err := handler.AddIP(ipInstance) if err != nil { t.Errorf("should not have errored, err : %v", err) } } func TestAddIPDup(t *testing.T) { err := handler.AddIP(ipInstance) if err == nil { t.Errorf("should have errored for duplicate IP") } } func TestGetAllIPsAfterAdd(t *testing.T) { ips, err := handler.GetAllIPs() if err != nil { t.Errorf("should not have errored, err : %v", err) } if len(ips) == 0 { t.Errorf("should have included %v , instead got : %v", ipAddr, ips) } } func TestCheckIPExistsFileError(t *testing.T) { changeFilePermission("100") _, err := handler.CheckIPExists(ipAddr) if err == nil { t.Errorf("should have errored") } if err != nil && strings.Index(err.Error(), "permission denied") == -1 { t.Errorf("should have received permission error, instead got : %v", err) } changeFilePermission("644") } func TestCheckIPExists(t *testing.T) { ipExists, err := handler.CheckIPExists(ipAddr) if err != nil { t.Errorf("should not have errored, err : %v", err) } if !ipExists { t.Errorf("ip %v should exist", ipAddr) } } func TestGetIPFileError(t *testing.T) { changeFilePermission("100") _, err := handler.GetIP(ipAddr) if err == nil { t.Errorf("should have errored") } if err != nil && strings.Index(err.Error(), "permission denied") == -1 { t.Errorf("should have received permission error, instead got : %v", err) } changeFilePermission("644") } func TestGetInvalidIP(t *testing.T) { _, err := handler.GetIP("invalid_ip") if err == nil { t.Errorf("should have errored") } if err != nil && err.Error() != "record not found" { t.Errorf("record should not have been found, instead got : %v", err) } } func TestGetIP(t *testing.T) { ipRecd, err := handler.GetIP(ipAddr) if err != nil { t.Errorf("should not have errored, err : %v", err) } if ipRecd.IP != ipInstance.IP { t.Errorf("ip should be same, got %v want %v", ipRecd.IP, ipInstance.IP) } } func TestDeleteIPFileError(t *testing.T) { changeFilePermission("100") _, err := handler.DeleteIP(ipAddr) if err == nil { t.Errorf("should have errored") } if err != nil && strings.Index(err.Error(), "permission denied") == -1 { t.Errorf("should have received permission error, instead got : %v", err) } changeFilePermission("500") _, err = handler.DeleteIP(ipAddr) if err == nil { t.Errorf("should have errored") } if err != nil && strings.Index(err.Error(), "permission denied") == -1 { t.Errorf("should have received permission error, instead got : %v", err) } changeFilePermission("644") } func TestDeleteInvalidIP(t *testing.T) { _, err := handler.DeleteIP("invalid_ip") if err == nil { t.Errorf("should have errored") } if err != nil && err.Error() != "record not found" { t.Errorf("record should not have been found, instead got : %v", err) } } func TestDeleteIP(t *testing.T) { ipDeleted, err := handler.DeleteIP(ipAddr) if err != nil { t.Errorf("should not have errored, err : %v", err) } if ipAddr != ipDeleted.IP { t.Errorf("ip %v should be the same", ipAddr) } ipExists, err := handler.CheckIPExists(ipAddr) if err != nil { t.Errorf("should not have errored, err : %v", err) } if ipExists { t.Errorf("ip %v should be deleted", ipAddr) } } func changeFilePermission(permission string) { cmd := exec.Command("chmod", permission, "firewalld-rest.db") err := cmd.Run() if err != nil { log.Fatalf("could not change permission of file, err : %v", err) } // cmd1 := exec.Command("ls", "-la") // o1, _ := cmd1.CombinedOutput() // fmt.Println("cmd1 : ", string(o1)) } ================================================ FILE: ip/ip.go ================================================ package ip // Instance holds json for ip and domain type Instance struct { IP string `json:"ip"` Domain string `json:"domain"` } //Handler interface for handling IP related tasks type Handler interface { GetIP(string) (*Instance, error) GetAllIPs() ([]*Instance, error) CheckIPExists(ipAddr string) (bool, error) AddIP(ip *Instance) error DeleteIP(ipAddr string) (*Instance, error) } ================================================ FILE: k8s/ingress.yaml ================================================ apiVersion: extensions/v1beta1 kind: Ingress metadata: name: firewalld-ingress spec: rules: - host: http: #different paths for different hosts under the same k8s config paths: - path: /m1 backend: serviceName: external-rest servicePort: 80 - path: /m2 backend: serviceName: external-rest-2 servicePort: 80 - path: /m3 backend: serviceName: external-rest-3 servicePort: 80 ================================================ FILE: k8s/svc-nodeport.yaml ================================================ apiVersion: v1 kind: Service metadata: name: external-rest spec: externalIPs: - 169.xx.xx.xxx # public IP of the server type: NodePort ports: - name: firewalld protocol: TCP port: 8080 targetPort: 8080 --- apiVersion: v1 kind: Endpoints metadata: name: external-rest subsets: - addresses: - ip: 10.xx.xx.xx #private IP of server ports: - port: 8080 name: firewalld ================================================ FILE: k8s/svc.yaml ================================================ apiVersion: v1 kind: Service metadata: name: external-rest #external-rest-2 for 2nd machine and so on spec: ports: - name: firewalld protocol: TCP port: 80 targetPort: 8080 --- apiVersion: v1 kind: Endpoints metadata: name: external-rest #external-rest-2 for 2nd machine and so on subsets: - addresses: - ip: 10.xx.xx.xx #private IP of node ports: - port: 8080 name: firewalld ================================================ FILE: route/handler.go ================================================ package route import ( "encoding/json" "fmt" "io" "io/ioutil" "log" "net/http" "os" "github.com/gorilla/mux" "github.com/prashantgupta24/firewalld-rest/firewallcmd" "github.com/prashantgupta24/firewalld-rest/ip" ) //Index page // GET / func Index(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Welcome!\n") } // IPAdd for the Create action // POST /ip func IPAdd(w http.ResponseWriter, r *http.Request) { ipInstance := &ip.Instance{} if err := populateModelFromHandler(w, r, ipInstance); err != nil { writeErrorResponse(w, http.StatusUnprocessableEntity, "Unprocessible Entity") return } ipExists, err := ip.GetHandler().CheckIPExists(ipInstance.IP) if err != nil { writeErrorResponse(w, http.StatusInternalServerError, err.Error()) return } if ipExists { writeErrorResponse(w, http.StatusBadRequest, "ip already exists") return } env := os.Getenv("env") if env != "local" { command, err := firewallcmd.EnableRichRuleForIP(ipInstance.IP) if err != nil { writeErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("cannot exec command %v, err : %v", command, err.Error())) return } } err = ip.GetHandler().AddIP(ipInstance) if err != nil { writeErrorResponse(w, http.StatusInternalServerError, err.Error()) return } writeOKResponse(w, ipInstance) } // IPShow for the ip Show action // GET /ip/{ip} func IPShow(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ipAddr := vars["ip"] ip, err := ip.GetHandler().GetIP(ipAddr) if err != nil { // No IP found writeErrorResponse(w, http.StatusNotFound, err.Error()) return } writeOKResponse(w, ip) } // ShowAllIPs shows all IPs // GET /ip func ShowAllIPs(w http.ResponseWriter, r *http.Request) { ips, err := ip.GetHandler().GetAllIPs() if err != nil { writeErrorResponse(w, http.StatusInternalServerError, err.Error()) return } writeOKResponse(w, ips) } // IPDelete for the ip Delete action // DELETE /ip/{ip} func IPDelete(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) ipAddr := vars["ip"] log.Printf("IP to delete %s\n", ipAddr) ipExists, err := ip.GetHandler().CheckIPExists(ipAddr) if err != nil { writeErrorResponse(w, http.StatusInternalServerError, err.Error()) return } if !ipExists { writeErrorResponse(w, http.StatusNotFound, "ip does not exist") return } env := os.Getenv("env") if env != "local" { command, err := firewallcmd.DisableRichRuleForIP(ipAddr) if err != nil { writeErrorResponse(w, http.StatusInternalServerError, fmt.Sprintf("cannot exec command %v, err : %v", command, err.Error())) return } } ip, err := ip.GetHandler().DeleteIP(ipAddr) if err != nil { // IP could not be deleted writeErrorResponse(w, http.StatusNotFound, err.Error()) return } writeOKResponse(w, ip) } // Writes the response as a standard JSON response with StatusOK func writeOKResponse(w http.ResponseWriter, m interface{}) { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(&JSONResponse{Data: m}); err != nil { writeErrorResponse(w, http.StatusInternalServerError, "Internal Server Error") } } // Writes the error response as a Standard API JSON response with a response code func writeErrorResponse(w http.ResponseWriter, errorCode int, errorMsg string) { w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(errorCode) json. NewEncoder(w). Encode(&JSONErrorResponse{Error: &APIError{Status: errorCode, Title: errorMsg}}) } //Populates a ip from the params in the Handler func populateModelFromHandler(w http.ResponseWriter, r *http.Request, ip interface{}) error { body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576)) if err != nil { return err } if err := r.Body.Close(); err != nil { return err } if err := json.Unmarshal(body, ip); err != nil { return err } return nil } ================================================ FILE: route/handler_test.go ================================================ package route import ( "net/http" "net/http/httptest" "os" "strings" "testing" "github.com/gorilla/mux" "github.com/prashantgupta24/firewalld-rest/ip" ) var data1 string var data2 string var dataInvalid string var ipAddr1 string var ipAddr2 string var ipAddr3 string func setup() { ipAddr1 = "10.20.30.40" ipAddr2 = "20.40.60.80" ipAddr3 = "10.50.100.150" data1 = `{"ip":"` + ipAddr1 + `","domain":"test.com"}` data2 = `{"ip":"` + ipAddr2 + `","domain":"test.com"}` dataInvalid = `{"ip":"` + ipAddr2 //missing domain } func shutdown() { os.Remove("firewalld-rest.db") } func TestMain(m *testing.M) { setup() code := m.Run() shutdown() os.Exit(code) } func TestIndex(t *testing.T) { req, err := http.NewRequest("GET", "/", nil) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, Index) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `Welcome!` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestShowAllIPs(t *testing.T) { req, err := http.NewRequest("GET", "/ip", nil) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, ShowAllIPs) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"meta":null,"data":[]}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestAddBadIP(t *testing.T) { req, err := http.NewRequest("POST", "/ip", strings.NewReader(dataInvalid)) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, IPAdd) if status := rr.Code; status != http.StatusUnprocessableEntity { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"error":{"status":422,"title":"Unprocessible Entity"}}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestAddIPNonLocal(t *testing.T) { oldEnv := os.Getenv("env") os.Setenv("env", "staging") req, err := http.NewRequest("POST", "/ip", strings.NewReader(data1)) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, IPAdd) if status := rr.Code; status != http.StatusInternalServerError { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `cannot exec command ` if strings.Index(rr.Body.String(), expected) == -1 { t.Errorf("handler returned unexpected body: \ngot %v should have included : %v", rr.Body.String(), expected) } os.Setenv("env", oldEnv) } func TestAddIP(t *testing.T) { req, err := http.NewRequest("POST", "/ip", strings.NewReader(data1)) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, IPAdd) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"meta":null,"data":` + data1 + `}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestAddIPDup(t *testing.T) { req, err := http.NewRequest("POST", "/ip", strings.NewReader(data1)) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, IPAdd) if status := rr.Code; status != http.StatusBadRequest { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"error":{"status":400,"title":"ip already exists"}}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestShowIP(t *testing.T) { req, err := http.NewRequest("GET", "/ip/"+ipAddr1, nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() router := mux.NewRouter() router.HandleFunc("/ip/{ip}", IPShow) router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"meta":null,"data":` + data1 + `}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestShowIPNotFound(t *testing.T) { req, err := http.NewRequest("GET", "/ip/"+ipAddr3, nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() router := mux.NewRouter() router.HandleFunc("/ip/{ip}", IPShow) router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"error":{"status":404,"title":"record not found"}}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestAddIP2(t *testing.T) { req, err := http.NewRequest("POST", "/ip", strings.NewReader(data2)) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, IPAdd) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"meta":null,"data":` + data2 + `}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestShowAllIPsAfterAdding(t *testing.T) { req, err := http.NewRequest("GET", "/ip", nil) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, ShowAllIPs) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //make sure both IPs exist if strings.Index(rr.Body.String(), ipAddr1) == -1 || strings.Index(rr.Body.String(), ipAddr2) == -1 { t.Errorf("handler returned without required body: \ngot %v want %v", rr.Body.String(), ipAddr1) } } func TestDeleteIPNonLocal(t *testing.T) { oldEnv := os.Getenv("env") os.Setenv("env", "staging") req, err := http.NewRequest("DELETE", "/ip/"+ipAddr1, nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() router := mux.NewRouter() router.HandleFunc("/ip/{ip}", IPDelete) router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusInternalServerError { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `cannot exec command ` if strings.Index(rr.Body.String(), expected) == -1 { t.Errorf("handler returned unexpected body: \ngot %v should have included : %v", rr.Body.String(), expected) } os.Setenv("env", oldEnv) } func TestDeleteIP(t *testing.T) { req, err := http.NewRequest("DELETE", "/ip/"+ipAddr1, nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() router := mux.NewRouter() router.HandleFunc("/ip/{ip}", IPDelete) router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } // Check the response body is what we expect. expected := `{"meta":null,"data":` + data1 + `}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestDeleteIPNotFound(t *testing.T) { req, err := http.NewRequest("DELETE", "/ip/"+ipAddr1, nil) if err != nil { t.Fatal(err) } rr := httptest.NewRecorder() router := mux.NewRouter() router.HandleFunc("/ip/{ip}", IPDelete) router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusNotFound { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound) } // Check the response body is what we expect. expected := `{"error":{"status":404,"title":"ip does not exist"}}` if strings.TrimSpace(rr.Body.String()) != expected { t.Errorf("handler returned unexpected body: \ngot %v want %v", rr.Body.String(), expected) } } func TestShowAllIPsAfter(t *testing.T) { req, err := http.NewRequest("GET", "/ip", nil) if err != nil { t.Fatal(err) } rr := newRequestRecorder(req, ShowAllIPs) if status := rr.Code; status != http.StatusOK { t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusOK) } //make sure ip doesn't exist if strings.Index(rr.Body.String(), ipAddr1) != -1 { t.Errorf("handler contained deleted entry: \ngot %vdeleted %v", rr.Body.String(), ipAddr1) } } func TestPopulateModelFromHandler(t *testing.T) { req, err := http.NewRequest("POST", "/ip", strings.NewReader("garbage")) if err != nil { t.Fatal(err) } ipInstance := &ip.Instance{} if err := populateModelFromHandler(nil, req, ipInstance); err == nil { t.Errorf("should have errored") } req, err = http.NewRequest("POST", "/ip", strings.NewReader(dataInvalid)) if err != nil { t.Fatal(err) } ipInstance = &ip.Instance{} if err := populateModelFromHandler(nil, req, ipInstance); err == nil { t.Errorf("should have errored") } req, err = http.NewRequest("POST", "/ip", strings.NewReader(data1)) if err != nil { t.Fatal(err) } ipInstance = &ip.Instance{} if err := populateModelFromHandler(nil, req, ipInstance); err != nil { t.Errorf("should not have errored : %v", err) } } // Mocks a handler and returns a httptest.ResponseRecorder func newRequestRecorder(req *http.Request, fnHandler func(w http.ResponseWriter, r *http.Request)) *httptest.ResponseRecorder { rr := httptest.NewRecorder() handler := http.HandlerFunc(fnHandler) handler.ServeHTTP(rr, req) return rr } ================================================ FILE: route/middleware.go ================================================ package route import ( "encoding/json" "fmt" "log" "net/http" "strings" "github.com/dgrijalva/jwt-go" ) type exception struct { Message string `json:"message"` } //validateMiddleware validates the JWT func validateMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { authorizationHeader := req.Header.Get("authorization") if authorizationHeader != "" { //fmt.Println("authorizationHeader : ", authorizationHeader) bearerToken := strings.Split(authorizationHeader, " ") if len(bearerToken) == 2 { key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(publicCertContent)) if err != nil { json.NewEncoder(w).Encode(exception{Message: err.Error()}) return } token, error := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, fmt.Errorf("There was an error") } return key, nil }) if error != nil { json.NewEncoder(w).Encode(exception{Message: error.Error()}) return } if token.Valid { next.ServeHTTP(w, req) } else { json.NewEncoder(w).Encode(exception{Message: "Invalid authorization token"}) } } } else { json.NewEncoder(w).Encode(exception{Message: "An authorization header is required"}) } }) } func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Do stuff here log.Println(r.RequestURI) // Call the next handler, which can be another middleware in the chain, or the final handler. next.ServeHTTP(w, r) }) } ================================================ FILE: route/publicCert.go ================================================ package route //publicCertContent required for authentication const publicCertContent = ` -----BEGIN CERTIFICATE----- MIIDgjCCAmoCCQDybHZ/ZguMATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMC VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExETAPBgNVBAcMCFNhbiBKb3NlMQwwCgYD VQQKDANJQk0xFDASBgNVBAsMC0RhdGEgYW5kIEFJMScwJQYJKoZIhvcNAQkBFhhw cmFzaGFudGd1cHRhQHVzLmlibS5jb20wHhcNMjAwNjExMjA1MDU1WhcNMjAwNzEx MjA1MDU1WjCBgjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExETAP BgNVBAcMCFNhbiBKb3NlMQwwCgYDVQQKDANJQk0xFDASBgNVBAsMC0RhdGEgYW5k IEFJMScwJQYJKoZIhvcNAQkBFhhwcmFzaGFudGd1cHRhQHVzLmlibS5jb20wggEi MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDnQKV05br1v8+lyt+js9Lhhpej QEjLQvWKkeWIC+VwXekXIrraM8Z1MImI9hAGDgyK7b18uk3paZ7KxTxtaWxVodUU 75qDEsPRy8byQjAdDKnccMvDI1LMQ1HHw6Hfv8GEOcBebKwdsbtpBYtqKsaZn95N Iw8k2alDAUVe8y840lTzOhowsaN9I4bQV2nNosfWWYGOCacV8vIquJ0s71BdFk7A gXAO4vONEwrpJICiBRQRWTcKFNeCBoNn5zNFs0LsncrhKajENeXT+NfLJUVLEwTc 0X0yqz587rlQrKY7/xDQukVhGq1HCRMeWbeK87/jcTf8QyQu4nbqrgAJPzQBAgMB AAEwDQYJKoZIhvcNAQELBQADggEBALhCTiALoDxLpa3KK3utgBG7VUcz3pbhnCdp Qj1y/U3lQ5Am+Lztc9V0CpbVRlX/B2Kmj3Eln+JOPnucHFOv4VbY6cE7oOIzgcAY Tp6/rn1KFXlb72cRahpFgnP7m2WWKXDibHNx7H4nGpmDNjMgmCgLP4KisauMrork CTEqVJk5abC/JCO7HBUBZkCsY0GgxmZDivWcpzxHjl7/U5dSlUEIlbcrmBaVN3fy aATm38m1e1h/ZE2gQRmfumA9DMEs3HJ4fLbEnpxJ+dJJM6uu7/jJaz1aPvNaNYby sAFLryXHIMWAKDO6o02IhcFpbw0T4GxpTYqsEcj7BrdbFdsUeN0= -----END CERTIFICATE----- ` ================================================ FILE: route/response.go ================================================ package route // JSONResponse defines meta and interface struct type JSONResponse struct { // Reserved field to add some meta information to the API response Meta interface{} `json:"meta"` Data interface{} `json:"data"` } // JSONErrorResponse defines error struct type JSONErrorResponse struct { Error *APIError `json:"error"` } // APIError defines api error struct type APIError struct { Status int `json:"status"` Title string `json:"title"` } ================================================ FILE: route/route.go ================================================ package route import ( "net/http" "github.com/gorilla/mux" ) type route struct { Name string Method string Pattern string HandlerFunc http.HandlerFunc } type routes []route //NewRouter creates a new mux router for application func NewRouter() *mux.Router { router := mux.NewRouter() subrouter := router.PathPrefix("/m{[0-9]+}").Subrouter().StrictSlash(true) subrouter.Use(loggingMiddleware, validateMiddleware) for _, route := range routesForApp { subrouter. Methods(route.Method). Path(route.Pattern). Name(route.Name). Handler(route.HandlerFunc) } return subrouter } var routesForApp = routes{ route{ "Index Page", "GET", "/", Index, }, route{ "Add New IP", "POST", "/ip", IPAdd, }, route{ "Show all IPs present", "GET", "/ip", ShowAllIPs, }, route{ "Show if particular IP is present", "GET", "/ip/{ip}", IPShow, }, route{ "Delete IP", "DELETE", "/ip/{ip}", IPDelete, }, }