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

support allowlist during registration #105

Merged
merged 6 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions cmd/mbop/mbop.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ func main() {
r.Post("/v1/registrations", handlers.RegistrationCreateHandler)
r.Delete("/v1/registrations/{uid}", handlers.RegistrationDeleteHandler)
r.Get("/v1/registrations/token", handlers.TokenHandler)

r.Get("/v1/allowlist", handlers.AllowlistListHandler)
r.Post("/v1/allowlist", handlers.AllowlistCreateHandler)
r.Delete("/v1/allowlist/{address}", handlers.AllowlistDeleteHandler)
})

err := mailer.InitConfig()
Expand Down
5 changes: 5 additions & 0 deletions deployments/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ objects:
value: ${TOKEN_TTL_DURATION}
- name: STORE_BACKEND
value: ${STORE_BACKEND}
- name: ALLOWLIST_ENABLED
value: ${ALLOWLIST_ENABLED}
- name: DISABLE_CATCHALL
value: ${DISABLE_CATCHALL}
- name: IS_INTERNAL_LABEL
Expand Down Expand Up @@ -325,3 +327,6 @@ parameters:
- name: CERT_DIR
description: the base directory where ssl certs are stored
value: "/certs"
- name: ALLOWLIST_ENABLED
description: whether to check registrations against the internal allowlist
value: "false"
3 changes: 3 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ type MbopConfig struct {
KeyCloakTokenGrantType string
KeyCloakTokenClientID string

AllowlistEnabled bool
StoreBackend string
DatabaseHost string
DatabasePort string
Expand All @@ -61,6 +62,7 @@ func Get() *MbopConfig {
}

disableCatchAll, _ := strconv.ParseBool(fetchWithDefault("DISABLE_CATCHALL", "false"))
allowlistEnabled, _ := strconv.ParseBool(fetchWithDefault("ALLOWLIST_ENABLED", "false"))
debug, _ := strconv.ParseBool(fetchWithDefault("DEBUG", "false"))
certDir := fetchWithDefault("CERT_DIR", "/certs")
keyCloakTimeout, _ := strconv.ParseInt(fetchWithDefault("KEYCLOAK_TIMEOUT", "60"), 0, 64)
Expand Down Expand Up @@ -90,6 +92,7 @@ func Get() *MbopConfig {
DatabasePassword: fetchWithDefault("DATABASE_PASSWORD", ""),
DatabaseName: fetchWithDefault("DATABASE_NAME", "mbop"),
StoreBackend: fetchWithDefault("STORE_BACKEND", "memory"),
AllowlistEnabled: allowlistEnabled,

CognitoAppClientID: fetchWithDefault("COGNITO_APP_CLIENT_ID", ""),
CognitoAppClientSecret: fetchWithDefault("COGNITO_APP_CLIENT_SECRET", ""),
Expand Down
107 changes: 107 additions & 0 deletions internal/handlers/allowlist_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package handlers

import (
"encoding/json"
"errors"
"net/http"
"time"

"github.com/go-chi/chi/v5"
l "github.com/redhatinsights/mbop/internal/logger"
"github.com/redhatinsights/mbop/internal/store"
"github.com/redhatinsights/platform-go-middlewares/identity"
)

type allowlistCreateRequest struct {
IP string `json:"ip"`
}

type allowListResponse struct {
IP string `json:"ip"`
OrgID string `json:"org_id"`
CreatedAt time.Time `json:"created_at"`
}

func AllowlistCreateHandler(w http.ResponseWriter, r *http.Request) {
id := identity.Get(r.Context())
if !id.Identity.User.OrgAdmin {
doError(w, "user must be org admin to add addresses to allowlist", 403)
return
}

var createReq allowlistCreateRequest
err := json.NewDecoder(r.Body).Decode(&createReq)
if err != nil {
do400(w, "invalid json in body - only expected key is [ip]")
return
}

db := store.GetStore()

err = db.AllowAddress(&store.Address{IP: createReq.IP, OrgID: id.Identity.OrgID})
if err != nil {
do500(w, "error storing address: "+err.Error())
return
}

w.WriteHeader(201)
}

func AllowlistDeleteHandler(w http.ResponseWriter, r *http.Request) {
id := identity.Get(r.Context())
if !id.Identity.User.OrgAdmin {
doError(w, "user must be org admin to add addresses to allowlist", 403)
return
}

ip := chi.URLParam(r, "address")
if ip == "" {
do400(w, "need address in path in the form `/v1/allowlist/{address}")
return
}

db := store.GetStore()

err := db.DenyAddress(&store.Address{IP: ip})
if err != nil {
if errors.Is(err, store.ErrAddressNotAllowListed) {
doError(w, "ip not allowlisted", 404)
return
}

do500(w, "error deleting addressaddress: %w"+err.Error())
return
}

w.WriteHeader(204)
}

func AllowlistListHandler(w http.ResponseWriter, r *http.Request) {
id := identity.Get(r.Context())
if !id.Identity.User.OrgAdmin {
doError(w, "user must be org admin to add addresses to allowlist", 403)
return
}

db := store.GetStore()

addrs, err := db.AllowedAddresses(id.Identity.OrgID)
if err != nil {
do500(w, "error listing addresses: %w"+err.Error())
return
}

out := make([]allowListResponse, len(addrs))
for i, addr := range addrs {
out[i] = allowListResponse{
IP: addr.IP,
OrgID: addr.OrgID,
CreatedAt: addr.CreatedAt,
}
}

err = json.NewEncoder(w).Encode(out)
if err != nil {
l.Log.Info("failed to encode response", "error", err)
}
}
21 changes: 19 additions & 2 deletions internal/handlers/registration_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"time"

"github.com/go-chi/chi/v5"
"github.com/redhatinsights/mbop/internal/config"
"github.com/redhatinsights/mbop/internal/store"
"github.com/redhatinsights/platform-go-middlewares/identity"
)
Expand Down Expand Up @@ -77,6 +78,24 @@ func RegistrationListHandler(w http.ResponseWriter, r *http.Request) {
}

func RegistrationCreateHandler(w http.ResponseWriter, r *http.Request) {
id := identity.Get(r.Context())
db := store.GetStore()

if config.Get().AllowlistEnabled {
allowed, err := db.AllowedIP(&store.Address{
IP: r.Header.Get("x-forwarded-for"),
lindgrenj6 marked this conversation as resolved.
Show resolved Hide resolved
OrgID: id.Identity.OrgID,
})
if err != nil {
do500(w, "error listing ip addresses: "+err.Error())
return
}
if !allowed {
doError(w, "address is not allowlisted", 403)
return
}
}

b, err := io.ReadAll(r.Body)
if err != nil {
do500(w, "failed to read body bytes: "+err.Error())
Expand All @@ -100,7 +119,6 @@ func RegistrationCreateHandler(w http.ResponseWriter, r *http.Request) {
return
}

id := identity.Get(r.Context())
if !id.Identity.User.OrgAdmin {
doError(w, "user must be org admin to register satellite", 403)
return
Expand All @@ -121,7 +139,6 @@ func RegistrationCreateHandler(w http.ResponseWriter, r *http.Request) {
return
}

db := store.GetStore()
_, err = db.Create(&store.Registration{
OrgID: id.Identity.OrgID,
Username: id.Identity.User.Username,
Expand Down
5 changes: 4 additions & 1 deletion internal/store/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import (
"reflect"
)

var ErrRegistrationNotFound = errors.New("registration not found")
var (
ErrRegistrationNotFound = errors.New("registration not found")
ErrAddressNotAllowListed = errors.New("ip not registered in allowlist")
)

// error type containing information on why a registration already exists
type ErrRegistrationAlreadyExists struct {
Expand Down
33 changes: 31 additions & 2 deletions internal/store/in_memory_store_impl.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package store

import "time"
import (
"time"
)

type inMemoryStore struct {
db []Registration
db []Registration
allowedAddresses []Address
}

func (m *inMemoryStore) All(orgID string, _, _ int) ([]Registration, int, error) {
Expand Down Expand Up @@ -72,3 +75,29 @@ func (m *inMemoryStore) Delete(orgID string, uid string) error {

return ErrRegistrationNotFound
}

func (m *inMemoryStore) AllowedAddresses(_ string) ([]Address, error) {
return m.allowedAddresses, nil
}
func (m *inMemoryStore) AllowedIP(ip *Address) (bool, error) {
for _, addr := range m.allowedAddresses {
if ip.IP == addr.IP {
return true, nil
}
}
return false, nil
}
func (m *inMemoryStore) AllowAddress(ip *Address) error {
m.allowedAddresses = append(m.allowedAddresses, *ip)
return nil
}
func (m *inMemoryStore) DenyAddress(ip *Address) error {
for i := range m.allowedAddresses {
if m.allowedAddresses[i].OrgID == ip.OrgID && m.allowedAddresses[i].IP == ip.IP {
m.allowedAddresses = append(m.allowedAddresses[:i], m.allowedAddresses[i+1:]...)
return nil
}
}

return ErrAddressNotAllowListed
}
2 changes: 1 addition & 1 deletion internal/store/in_memory_store_impl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

type InMemoryStoreTestSuite struct {
suite.Suite
store Store
store RegistrationStore
}

func (suite *InMemoryStoreTestSuite) SetupSuite() {}
Expand Down
12 changes: 12 additions & 0 deletions internal/store/interface.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package store

type Store interface {
RegistrationStore
AllowlistStore
}

type RegistrationStore interface {
All(orgID string, limit, offset int) ([]Registration, int, error)
// Find a registration that both the org ID + UID match
Find(orgID, uid string) (*Registration, error)
Expand All @@ -10,3 +15,10 @@ type Store interface {
Update(r *Registration, update *RegistrationUpdate) error
Delete(orgID, uid string) error
}

type AllowlistStore interface {
AllowedAddresses(orgID string) ([]Address, error)
AllowedIP(ip *Address) (bool, error)
AllowAddress(ip *Address) error
DenyAddress(ip *Address) error
}
1 change: 1 addition & 0 deletions internal/store/migrations/5_add_allowlist.down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
drop table if exists public.allowlist;
5 changes: 5 additions & 0 deletions internal/store/migrations/5_add_allowlist.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
create table if not exists public.allowlist(
ip varchar not null,
org_id varchar not null,
created_at timestamp default now() not null
);
74 changes: 71 additions & 3 deletions internal/store/postgres_store_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,9 @@ func (p *postgresStore) FindByUID(uid string) (*Registration, error) {

func (p *postgresStore) Create(r *Registration) (string, error) {
res := p.db.QueryRow(
`insert into registrations
(org_id, username, uid, display_name, extra)
values ($1, $2, $3, $4, $5)
`insert into registrations
(org_id, username, uid, display_name, extra)
values ($1, $2, $3, $4, $5)
returning id`,
r.OrgID,
r.Username,
Expand Down Expand Up @@ -171,3 +171,71 @@ func scanRegistration(row scanner) (*Registration, error) {
CreatedAt: createdAt,
}, nil
}

func (p *postgresStore) AllowedIP(ip *Address) (bool, error) {
res := p.db.QueryRow(`select 1
from allowlist
where ip = $1 and org_id = $2 limit 1`,
lindgrenj6 marked this conversation as resolved.
Show resolved Hide resolved
ip.IP, ip.OrgID)

var found int
err := res.Scan(&found)
if err != nil {
return false, nil
}

return found == 1, nil
}

func (p *postgresStore) AllowAddress(ip *Address) error {
_, err := p.db.Exec(`insert into allowlist (ip, org_id) values ($1, $2)`, ip.IP, ip.OrgID)
return err
}

func (p *postgresStore) DenyAddress(ip *Address) error {
res, err := p.db.Exec(`delete from allowlist where ip=$1`, ip.IP)
if err != nil {
return err
}

rows, err := res.RowsAffected()
if err != nil {
return err
}
if rows == 0 {
return ErrAddressNotAllowListed
}

return nil
}

func (p *postgresStore) AllowedAddresses(orgID string) ([]Address, error) {
rows, err := p.db.Query(`select
org_id, ip, created_at
from allowlist
where org_id = $1`, orgID)
if err != nil {
return nil, err
}

addresses := make([]Address, 0)
for rows.Next() {
var (
orgID string
address string
createdAt time.Time
)

err = rows.Scan(&orgID, &address, &createdAt)
if err != nil {
return nil, err
}

addresses = append(addresses, Address{
IP: address,
OrgID: orgID,
CreatedAt: createdAt,
})
}
return addresses, nil
}
2 changes: 1 addition & 1 deletion internal/store/postgres_store_impl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
type TestSuite struct {
suite.Suite
db *sql.DB
store Store
store RegistrationStore
}

func (suite *TestSuite) SetupSuite() {
Expand Down
Loading
Loading