Skip to content

Commit

Permalink
Fix gateway-profile authorization for api keys.
Browse files Browse the repository at this point in the history
Closes #525.
  • Loading branch information
brocaar committed Aug 26, 2020
1 parent 7660886 commit 20e26d5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 5 deletions.
35 changes: 30 additions & 5 deletions internal/api/external/auth/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -1085,30 +1085,55 @@ func ValidateOrganizationUserAccess(flag Flag, organizationID, userID int64) Val
// ValidateGatewayProfileAccess validates if the client has access
// to the gateway-profiles.
func ValidateGatewayProfileAccess(flag Flag) ValidatorFunc {
query := `
userQuery := `
select
1
from
"user" u
`

var where = [][]string{}
apiKeyQuery := `
select
1
from
api_key ak
`

var userWhere = [][]string{}
var apiKeyWhere = [][]string{}

switch flag {
case Create, Update, Delete:
// global admin
where = [][]string{
userWhere = [][]string{
{"(u.email = $1 or u.id = $2)", "u.is_active = true", "u.is_admin = true"},
}

// admin api key
apiKeyWhere = [][]string{
{"ak.id = $1", "ak.is_admin = true"},
}
case Read, List:
// any active user
where = [][]string{
userWhere = [][]string{
{"(u.email = $1 or u.id = $2)", "u.is_active = true"},
}

// any api key
apiKeyWhere = [][]string{
{"ak.id = $1"},
}
}

return func(db sqlx.Queryer, claims *Claims) (bool, error) {
return executeQuery(db, query, where, claims.Username, claims.UserID)
switch claims.Subject {
case SubjectUser:
return executeQuery(db, userQuery, userWhere, claims.Username, claims.UserID)
case SubjectAPIKey:
return executeQuery(db, apiKeyQuery, apiKeyWhere, claims.APIKeyID)
default:
return false, nil
}
}
}

Expand Down
18 changes: 18 additions & 0 deletions internal/api/external/auth/validators_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,24 @@ func (ts *ValidatorTestSuite) TestGateway() {
Claims: Claims{UserID: users[2].id},
ExpectedOK: false,
},
{
Name: "admin api key can create, update, delete, read and list",
Validators: []ValidatorFunc{ValidateGatewayProfileAccess(Create), ValidateGatewayProfileAccess(Update), ValidateGatewayProfileAccess(Delete), ValidateGatewayProfileAccess(Read), ValidateGatewayProfileAccess(List)},
Claims: Claims{APIKeyID: apiKeys[0].ID},
ExpectedOK: true,
},
{
Name: "any api key can read and list",
Validators: []ValidatorFunc{ValidateGatewayProfileAccess(Read), ValidateGatewayProfileAccess(List)},
Claims: Claims{APIKeyID: apiKeys[3].ID},
ExpectedOK: true,
},
{
Name: "non-admin api keys can not create, update or delete",
Validators: []ValidatorFunc{ValidateGatewayProfileAccess(Create), ValidateGatewayProfileAccess(Update), ValidateGatewayProfileAccess(Delete)},
Claims: Claims{APIKeyID: apiKeys[1].ID},
ExpectedOK: false,
},
}

ts.RunTests(t, tests)
Expand Down

0 comments on commit 20e26d5

Please sign in to comment.