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 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
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", handlers.AllowlistDeleteHandler)
})

err := mailer.InitConfig()
Expand Down
10 changes: 10 additions & 0 deletions deployments/deployment.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ objects:
value: ${TOKEN_TTL_DURATION}
- name: STORE_BACKEND
value: ${STORE_BACKEND}
- name: ALLOWLIST_ENABLED
value: ${ALLOWLIST_ENABLED}
- name: ALLOWLIST_HEADER
value: ${ALLOWLIST_HEADER}
- name: DISABLE_CATCHALL
value: ${DISABLE_CATCHALL}
- name: IS_INTERNAL_LABEL
Expand Down Expand Up @@ -325,3 +329,9 @@ 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"
- name: ALLOWLIST_HEADER
description: which header to pull the current ip address from
value: "x-forwarded-for"
5 changes: 5 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ type MbopConfig struct {
KeyCloakTokenGrantType string
KeyCloakTokenClientID string

AllowlistEnabled bool
AllowlistHeader string
StoreBackend string
DatabaseHost string
DatabasePort string
Expand All @@ -61,6 +63,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 +93,8 @@ func Get() *MbopConfig {
DatabasePassword: fetchWithDefault("DATABASE_PASSWORD", ""),
DatabaseName: fetchWithDefault("DATABASE_NAME", "mbop"),
StoreBackend: fetchWithDefault("STORE_BACKEND", "memory"),
AllowlistEnabled: allowlistEnabled,
AllowlistHeader: fetchWithDefault("ALLOWLIST_HEADER", "x-forwarded-for"),

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

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

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

type allowlistCreateRequest struct {
IPBlock string `json:"ip_block"`
}

type allowListResponse struct {
IPBlock string `json:"ip_block"`
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
}

if !strings.Contains(createReq.IPBlock, "/") {
createReq.IPBlock += "/32"
}

_, _, err = net.ParseCIDR(createReq.IPBlock)
if err != nil {
do400(w, "invalid IP block, needs to be an IPv4 range or single IP")
return
}

db := store.GetStore()

err = db.AllowAddress(&store.AllowlistBlock{IPBlock: createReq.IPBlock, 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
}

block := r.URL.Query().Get("block")
if block == "" {
do400(w, "need address in path in the form `/v1/allowlist?block={block}")
return
}

db := store.GetStore()

err := db.DenyAddress(&store.AllowlistBlock{IPBlock: block, OrgID: id.Identity.OrgID})
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{
IPBlock: addr.IPBlock,
OrgID: addr.OrgID,
CreatedAt: addr.CreatedAt,
}
}

err = json.NewEncoder(w).Encode(out)
if err != nil {
l.Log.Info("failed to encode response", "error", err)
}
}
6 changes: 3 additions & 3 deletions internal/handlers/jwt_v1_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (suite *TestSuite) SetupSuite() {
}

func (suite *TestSuite) TestAwsJWTGetNoKid() {
suite.mockServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
suite.mockServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write(suite.testData)
}))
Expand Down Expand Up @@ -63,7 +63,7 @@ func (suite *TestSuite) TestAwsJWTGetNoKid() {
}

func (suite *TestSuite) TestAwsJWTGetNoKidMatch() {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write(suite.testData)
}))
Expand Down Expand Up @@ -92,7 +92,7 @@ func (suite *TestSuite) TestAwsJWTGetNoKidMatch() {
}

func (suite *TestSuite) TestAwsJWTGetKidMatch() {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write(suite.testData)
}))
Expand Down
18 changes: 16 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,21 @@ 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(r.Header.Get(config.Get().AllowlistHeader), 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 +116,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 +136,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
35 changes: 33 additions & 2 deletions internal/store/in_memory_store_impl.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package store

import "time"
import (
"net"
"time"
)

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

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

return ErrRegistrationNotFound
}

func (m *inMemoryStore) AllowedAddresses(_ string) ([]AllowlistBlock, error) {
return m.allowedAddresses, nil
}
func (m *inMemoryStore) AllowedIP(ip, _ string) (bool, error) {
for _, addr := range m.allowedAddresses {
_, ipnet, _ := net.ParseCIDR(addr.IPBlock)
if ipnet.Contains(net.ParseIP(ip)) {
return true, nil
}
}
return false, nil
}
func (m *inMemoryStore) AllowAddress(ip *AllowlistBlock) error {
m.allowedAddresses = append(m.allowedAddresses, *ip)
return nil
}
func (m *inMemoryStore) DenyAddress(ip *AllowlistBlock) error {
for i := range m.allowedAddresses {
if m.allowedAddresses[i].OrgID == ip.OrgID && m.allowedAddresses[i].IPBlock == ip.IPBlock {
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) ([]AllowlistBlock, error)
AllowedIP(ip, orgID string) (bool, error)
AllowAddress(ip *AllowlistBlock) error
DenyAddress(ip *AllowlistBlock) 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;
9 changes: 9 additions & 0 deletions internal/store/migrations/5_add_allowlist.up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
create table if not exists public.allowlist(
ip_block varchar not null,
org_id varchar not null,
created_at timestamp default now() not null
);

alter table if exists public.allowlist
add constraint allowlist_unique_cidr_per_org
primary key (ip_block, org_id);
Loading
Loading